0

Note: The variable is set in included file, the issue is not an undefined variable, hence the duplicate question is not relevant to my question. PHP: "Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset"

Edit: i just noted my localhost include path is set to C:\xampp\php\PEAR when i did echo get_include_path(); but i don't get error for included file not found rather the variable is undefined.

I have 2 files in C:/xampp/htdocs/test/ index.php config.php

Content of index.php:

require 'config.php';
echo $name;

Content of config.php:

$name = 'xyz';

And i get Notice: Undefined variable: name Where the $name = 'xyz' is in config.php which is included before using the variable.

I have to yet test it on live server. Please guide.

Community
  • 1
  • 1
Abdul Rehman
  • 1,662
  • 3
  • 22
  • 36
  • Possible duplicate of [PHP: "Notice: Undefined variable" and "Notice: Undefined index"](http://stackoverflow.com/questions/4261133/php-notice-undefined-variable-and-notice-undefined-index) – manniL Feb 16 '16 at 11:12
  • try to get errors using `error_reporting(E_ALL ^ E_NOTICE);` – PHPExpert Feb 16 '16 at 11:20
  • @PHPExpert hi, i tried as u suggested. it suppresses the notice and the name is never echoed this way. – Abdul Rehman Feb 16 '16 at 11:31
  • 1
    Use `require 'config.php';` instead of `include 'config.php';`. This will throw a fatal error if file is not found. – maxhb Feb 16 '16 at 11:32
  • @maxhb require/include same result, shows notice. i just notied my localhost include path is set to `C:\xampp\php\PEAR` when i did `echo get_include_path();` – Abdul Rehman Feb 16 '16 at 11:33
  • Use `require './config.php';` – maxhb Feb 16 '16 at 11:39
  • ^ same notice nothing changed. I think i have to set my include path to be the current directory instead of the one that is in my edit. – Abdul Rehman Feb 16 '16 at 11:41
  • Nope, i just tested. The problem is not with path. The config.php is being include. i made an invalid path and it did gave me file not found error. so the file is being included but the variableis not getting in included scope somehow. – Abdul Rehman Feb 16 '16 at 11:46

2 Answers2

2
    hi i tried your code but i didn't get any error..

    config.php

    <?php
    $name='hello';
    ?>

    index.php

    <?php
    require 'config.php';
    echo $name;
    ?>

include and require both are working
Max
  • 95
  • 9
0

Holly Cow.

There was no error in the file. The php start tag was not correct, it was short tag <? ?> instead of <?php ?> this was causing the issue.

i'm using php7 on my localhost. but of course t would work on older version of PHP and hosting.

Abdul Rehman
  • 1,662
  • 3
  • 22
  • 36