How to require_once from different directories?

这一生的挚爱 提交于 2019-12-01 20:51:14

The file does not exist.

The error message reads:

Warning: require_once(C:\xampp\htdocs\home\subfolder): failed to open stream:

And:

Failed opening required ''

Error messages never lie (well, almost never), therefore you are calling:

require_once('');

Realpath returns false for missing files

Realpath will return false if you pass it a path to a file that doesn't exist:

$return = realpath('this/doesnt/exist.foo'); // $return is false

Therefore, the argument passed to realpath doesn't refer to a file, which is the reason the path doesn't work.

Don't over use realpath

If you remove the use of realpath, you'll find that the error message is probably obvious. At a guess you're trying to include C:\xampp\htdocs\home\subfolder\libraries\database_library.php - because there is a missing . in this:

line 25 is require_once(realpath("./libraries/database_library.php"));

If instead you just define a root path:

define('ROOT', 'C:\xampp\htdocs\home\\');

Then you can use this constant with absolute confidence that these sort of problems wont occur:

require_once(ROOT . "libraries/database_library.php");

And if you do get the path wrong, the error message will make it obvious what the problem is.

You can use the PHP super global variable $_SERVER['DOCUMENT_ROOT'] to get the full path to your server document root, eg. /var/www/website/public.

The code could look like this:

require_once $_SERVER['DOCUMENT_ROOT'] . '/libraries/database_library.php';

This way you do not need to set the document root path manually; PHP will always pick it up for you and make it available in $_SERVER['DOCUMENT_ROOT'] in any PHP file that is within your server document root.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!