i have the following file structure:
rootDIR dir1 subdir1 file0.php file1.php dir2 file2.php file3.php file4.php
file1.php
requires file3 and file4 from dir2 like this :
require('../../dir2/file3.php')
file2.php
requires file1.php
like this :
require('../dir1/subdir1/file1.php')
BUT then require in file1 fails to open file3 and file4 ( maybe due to the path relativeness)
However what is the reason and what can I do for file2.php
so file1.php
properly require file3 and file4
Try adding dirname(__FILE__)
before the path, like:
require(dirname(__FILE__).'/../../dir2/file3.php');
It should include the file starting from the root directory
For relative paths you can use __DIR__
directly rather than dirname(__FILE__)
(as long as you are using PHP 5.3.0 and above):
require(__DIR__.'/../../dir2/file3.php');
Remember to add the additional forward slash at the beginning of the path within quotes.
See:
A proper advice here, is to never ever use such things as "../../" relative paths in your web apps. It's hard to read and terrible for maintenance.
As you can attest. It makes it extremely difficult to know what you are pointing to.
If you need to change the folder level of your application, or parts of it. It's completely prone to errors, and will likely break something that is horrible to debug.
Instead, define
a few constants in your bootstrap file for your main path(s) and then use:
require(MY_DIR.'/dir2/file3.php');
Moving your app from there, is as easy as replacing your MY_DIR constants in one single file.
You can always use the $_SERVER['DOCUMENT_ROOT']
as a valid starting point, as well, rather than resorting to a relative path. Just another option.
require($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
I think your cwd is dir2. Try :
require("file3.php");
require("file4.php");
来源:https://stackoverflow.com/questions/12954578/php-require-relative-path-error