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.
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.phpmight live in the same directory asb.php, but when the code is running, it is running in the context ofindex.php. If you had used__FILE__rather than__DIR__, you would see thata.phpreturns the same value asindex.phpwhen it is running as an included file onindex.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).