Why PHP "require" does not find a file?
When you use include or require, the file that you include will act as if it is part of the script that included it. In this case, the file a.php
might live in the same directory as b.php
, but when the code is running, it is running in the context of index.php
. If you had used __FILE__
rather than __DIR__
, you would see that a.php
returns the same value as index.php
when it is running as an included file on index.php
.
Since the relative path changes depending on where files are used, it's always best to use an absolute path relative to the server root. If the machine is configured normally, that will start with $_SERVER["DOCUMENT_ROOT"]
, then add the application path and the includes path. On some shared hosting servers, you might have to hard-code the root somewhere (or add it to the .htaccess file).
Misha Moroshko
I build products that make humans happier. Previously Front End engineer at Facebook. Now, reimagining live experiences at https://muso.live
Updated on June 05, 2022Comments
-
Misha Moroshko almost 2 years
I have the following files structure:
temp main index.php a.php b.php
Here are the files;
index.php
echo "index.php ---> " . __DIR__ . "<br />"; require('../a.php'); echo "OK<br />"
a.php
echo "a.php ---> " . __DIR__ . "<br />"; require('./b.php'); echo "a is here<br />"
b.php
echo "b is here<br />"
When
index.php
is called I got the following error:index.php ---> D:\Programs\WampServer 2\www\temp\main a.php ---> D:\Programs\WampServer 2\www\temp Warning: require(./b.php) [function.require]: failed to open stream: No such file or directory in D:\Programs\WampServer 2\www\temp\a.php on line 5 Fatal error: require() [function.require]: Failed opening required './b.php' (include_path='.;C:\php5\pear') in D:\Programs\WampServer 2\www\temp\a.php on line 5
I have noticed that if I change
require('./b.php');
to
require('b.php');
Why is that ? it works as expected.
-
Felix Kling over 13 yearsIncluding
a.php
seems to work, there is no error regarding this! -
Andrew Moore over 13 years-1: Slashes are also supported for cross-platform compatibility, as stated in the manual.
-
Phil over 13 yearsNo it doesn't. To be completely portable, you should use the
DIRECTORY_SEPARATOR
constant though either forward or backward slashes will work on Windows. -
mellowsoon over 13 years@Phil - PHP's own developers discourage the use of DIRECTORY_SEPARATOR.
-
Andrew Moore over 13 years@Phil Brown: PHP's core developers discourage the use of
DIRECTORY_SEPARATOR
and recommend using a forward slash/
. Also, yes, forward slashes are supported in Windows, see this manual page. -
Phil over 13 yearsI was simply taking a very pragmatic approach. DIRECTORY_SEPARATOR is also a hideously long constant name for what is only going to be a single character. The only reason to ever use it would be if a system did not support forward slash. To date, no system capable of running PHP exists AFAIK.