I’m trying to include a file but it doesn’t seem to be working – here’s the entire code:
if (file_exists('config/categories.php')) {
include ('config/categories.php');
}
foreach ($categories as $cat_sef => $cat_name) {
echo '<a href="'.$full_domain.$cat_sef.'" alt="#">'.$cat_name.'</a><br />';
}
The contents of config/categories.php is simply an array:
$categories = array("category-1" => "Category 1",
"category-2" => "Category 2",
"category-3" => "Category 3")
I know the file exists because the following works:
if (file_exists('config/categories.php')) {
echo "file exists";
}
However if I replace the array in categories.php with say:
echo "testing";
Nothing will display either. So as far as I can see, the file exists but it doesn’t seem to be including some how. If I rename the categories file to something else I will receive a ‘no such file’ error (file does not exist).
With the original code snippet, the error I get is:
Notice: Undefined variable: categories
But as you can see, it is defined in the categories.php file.
The ONLY way it works is to put the array in place of the if (file_exists) part of my code, which I don’t want to do because other parts rely on that categories.php file, so I don’t want to dupe an array in multiple files.
Does anyone have any idea what this could be? Let me know if you need any more info.
You have two options here :
use
include(dirname(__FILE__).'/config/categories.php')to make sure you are including this same file and not another ‘config/categories.php’double check that categories.php includes opening php tags like this
<?php. Seems obvious, but I have seen this more than once in code reviews.Hope this helps !