I am having trouble understanding how PHP chooses to compile or how including files within files works.
I require secrets.php
inside head.php
.
I require head.php
inside index.php
.
head.php
require "../environment/secrets.php";
index.php
require "php/head.php";
I get an error:
Warning: require_once(../environment/secrets.php): failed to open stream: No such file or directory in /home/ubuntu/workspace/Cally Dai/php/head.php on line 2 Call Stack: 0.0002 234760 1. {main}() /home/ubuntu/workspace/Cally Dai/index.php:0 0.0007 236632 2. require_once('/home/ubuntu/workspace/Cally Dai/php/head.php') /home/ubuntu/workspace/Cally Dai/index.php:5 Fatal error: require_once(): Failed opening required '../environment/secrets.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/ubuntu/workspace/Cally Dai/php/head.php on line 2 Call Stack: 0.0002 234760 1. {main}() /home/ubuntu/workspace/Cally Dai/index.php:0 0.0007 236632 2. require_once('/home/ubuntu/workspace/Cally Dai/php/head.php') /home/ubuntu/workspace/Cally Dai/index.php:5
where am I going wrong?
PHP will often report that it is unable to find the third file, but why? Well the answer lies in the fact that when including files in PHP the interpreter tries to find the file in the current working directory. In other words, if you run the script in a directory called A and you include a script that is found in directory B, then the relative path will be resolved relative to A when executing a script found in directory B. So, if the script inside directory B includes another file that is in a different directory, the path will still be calculated relative to A not relative to B as you might expect. This is a very important point to understand about the difference between PHP and other languages like C/C++.
One solution is to use dirname(__FILE__)
:
Use
dirname(__FILE__)
– The__FILE__
constant contains the full path and filename of the script that it is used in. The functiondirname()
removes the file name from the path, giving us the absolute path of the directory the file is in regardless of which script included it. Using this gives us the option of using relative paths just as we would with any other language, like C/C++. We would prefix all our relative path like this:
include(dirname(__FILE__) . "/dir/script_name.php");
Source: http://yagudaev.com/posts/resolving-php-relative-path-problem/