I've been confused due to the result being true in both cases, with or without using ABSPATH constant for this:

if (file_exists(ABSPATH . 'wp-config.php')){
    echo "true";
}

or

if (file_exists('wp-config.php')){
    echo "true";
}

Please note that the file running this code is not in the root directory (it's in a subfolder inside a plugin folder in wp-content/plugins directory).

Any explanation would be helpful please. Also which one should I prefer to use.

  • 1
    Is this file called with a direct request or is this a file included as plugin and request goes to index.php from WP root? – Krzysiek Dróżdż Dec 3 at 22:25
  • 1
    @KrzysiekDróżdż is on to it. The request is probably going to the index.php in the WP root and since wp-config.php is in the root, it will return a bool true. I think it's good practice to use ABSPATH for file_exists() all the time since the various wrappers supported by the function can result in some unexpected behavior. – jdp Dec 3 at 22:30

AFAIR, if you use file_exists with relative paths, you have to be very careful, because the path is relative to script that is called by request and not relative to file that contains that check...

So if it's a plugin and the request goes to main WP index.php, then you'll be looking for a file in WP root.

But if the same code will be run by AJAX call (wp-admin/admin-ajax.php) it will search for that file in wp-admin directory.

That's why you should use ABSPATH or use __DIR__ (to make the path relative to file in which you check the file existence).

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.