John Davidson

PHP include relative path

0 comments
Message:


I have file /root/update/test.php. There's also a file, /root/connect.php; This file has a line



include "../config.php";


In /root/update/test.php. There's the code



set_include_path(".:/root");
include "connect.php";


When I run /root/update/test.php, it finds connect.php, but fails to find config.php, giving me



PHP Warning:  include(../config.php): failed to open stream: No such file or directory in /root/connect.php on line 2
PHP Warning: include(): Failed opening '../config.php' for inclusion (include_path='.:/root')


This is confusing to me because the warnings make it seem like I'm doing everything correctly - the include path is /root, and it's looking for file ../config.php (/config.php), which exists. Can someone clear this up for me? Note that using absolute paths is not an option for me, due to deploying to a production server that I have no access to.



Ubuntu/Apache



My Answer:
The issue here is that the include path is set to ".:/root", which means that PHP will look for files relative to the current working directory first, and then in the /root directory. When you include "connect.php" from /root/update/test.php, the current working directory is /root/update, so PHP is looking for config.php in /root/update/../config.php, which does not exist.

To fix this issue, you can modify the include path in connect.php to include the parent directory as well. You can do this by adding "..:" to the include path like this:

php
set_include_path(".:/root:..");
include "config.php";


This way, PHP will first look for config.php in the current directory, and then in the parent directory (/root), which should resolve the issue.

Rate this post

5 of 5 based on 6769 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us