简体   繁体   中英

File_exists but won't include

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 !

You just included $categories inside if operator scope, so you can't use $categories outside. Just introduce $categories before inclusion

$categories = null;
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 />';
}

file_exists and include do not looking for file in the same way. include use the include_path option and search for your file in differents directory.

If you really want to know if a file can be included, you should use an absolute path.

An other thing. If your foreach ($categories code is inside a function, you need to define the $categories variable as global. Because include are always done in the global context.

如果您之前已经包含此文件,请使用include_once

If your file exists then please check php.ini file and set short_tag_open=on . It may works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM