Let me demonstrate my file structure first.
/www/
myfile.php
anotherC.php
a/
b.php
c.php
The code inside myfile.php is:
<?php
include_once("a/b.php");
?>
The code inside b.php is:
<?php
include_once("c.php");
?>
And finally inside c.php:
<?php
echo "hello i'm C.php";
?>
So, when I call www/myfile.php I get output:
hello i'm C.php
These works fine. But let me change b.php to
<?php
include_once("../anotherC.php"); //or include_once("./c.php"); (it won't work too)
?>
Now, when I call www/myfile.php, i get Error:
Warning: include_once(../anotherC.php): failed to open stream: No such
file or directory in /home/hasib/Desktop/www/a/b.php on line 2
Warning: include_once(): Failed opening '../anotherC.php' for
inclusion (include_path='.:/usr/share/php:/usr/share/pear') in
/home/hasib/Desktop/www/a/b.php on line 2
Now my question is, why The include_once("c.php"); worked perfectly??
the document:
If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.
If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.
the 'calling script' in your example is b.php , obviously it's directoy is '/www/a/'.
you can use getcwd() to get the 'current directory', either in myfile.php or b.php ,it will return '/www/'
so when include_once("c.php"); it first look up c.php in calling script's directory,that is /www/a/ , and get c.php successfully.
when include_once("../anotherC.php"); , it only look up anotherC.php in relative path to current directory, current directory is /www/ , so it look up anotherC.php in / , /anotherC.php doesn't exists and throw warning.
Includes with relative paths are always done relative to the MAIN script. include() operates essentially the same way as if you'd cut 'n pasted the included data directly into the main script. So when your sub-includes are performed, they're using the working directory of your myFile.php script, NOT the working directory of b.php or c.php.
Your sub-scripts would need to have an absolute path in their icnldues, or at least some kind of "where the heck am I" determination code, e.g. include(__FILE__ . 'c.php')
The only reason I can think of for this working is that you have /www/a in your include_path. This means that include_once("c.php") would first look for /www/c.php (since that's the current working directory), then look for /www/a/c.php which would be found and work.
However, include_once("./c.php") explicitly states to look in the current working directory only, and of course since the file is not there, it won't work.
Related
A. What does this do?
require ("./file.php");
B. in comparison to this?
require ("file.php");
(Its not up-one-directory.. which would be)
require ("../file.php");
./ is the current directory. It is largely the same as just file.php, but in many cases (this one included) it doesn't check any standard places PHP might look for a file, instead checking only the current directory.
From the PHP documentation (notice the last sentence):
Files for including are first looked for in each include_path entry relative to the current working directory, and then in the directory of current script. E.g. if your include_path is libraries, current working directory is /www/, you included include/a.php and there is include "b.php" in that file, b.php is first looked in /www/libraries/ and then in /www/include/. If filename begins with ./ or ../, it is looked only in the current working directory.
The first version forces the internal mechanism to include files relatively to the... directly executed file. So for example you have
index.php
// directly executed script (php -f index.php or from a browser)
include 'second.php';
second.php
// This is included relatively to index.php
// Actually, it is first searched relatively to include_path, then relatively
// to index.php
include './third.php';
third.php
// This is included relatively to second.php ONLY. It does not search
// include_path
return "foo";
The Short Answer
You're right, it's not up one directory. A . refers to the directory you're in, and .. refers to the parent directory.
Meaning, ./file.php and file.php are functionally equivalent in PHP. Here's the relavent page of documentation:
http://us.php.net/manual/en/wrappers.file.php
The Longer Answer
However, just because they work the same in this context doesn't mean they're always the same.
When you're operating in a *nix shell environment, and you type the name of an executable file, the shell will look in the PATH directories, but it won't look in the CWD, or the directory you're currently in.
So, if you're in a directory that has a file called: myprogram.php (this would be a PHP CLI file) and you just type:
myprogram.php
it doesn't matter if your program is executable or not. The shell will look in /bin/, /usr/bin/, etc. for your file, but it won't look in ./: the directory you're in.
To execute that program without adding your directory to the PATH, you need to type
./myprogram
So really, ./ is more explicit. It means, "the file you're looking for HAS to be right here" and lack of ./ means, "the file should be somewhere the program is looking for files".
The dot-slash forces the file to be found in the current directory only, rather than additionally searching the paths mentioned in the include_path setting.
Edit: I have completely rewritten the answer for the sake of clarity
When including a file, you can either use ./myfile.php or myfile.php.
They are not the same and you should always, preferably, use the first syntax, unless you know what you're doing.
The difference is best illustrated with an example: lets say you have the following files and folder structure:
index.php
inc/inner.php
From index.php, you can include your inner template without the ' ./' and it will work as expected:
# index.php
<?php
include "inc/inner.php";
Now let's say we add a new file, so the folder structure is now like this:
index.php
inc/inner.php
inc/inner-inner.php
To include inner-inner.php in inner.php, we would do this... right?
# src/inner.php
<?php
include "inner-inner.php";
Wrong. inner.php will just look for inner-inner.php in the root folder.
index.php
* inner-inner.php <- Doesn't exist, PHP ERROR.
inc/inner.php
inc/inner-inner.php
Instead, we should use the ./ syntax to include inner-inner. This will instruct that the file we are including must be included relative to the current file, not to the current "entry point" of the PHP script (index.php in the example).
# src/inner.php
<?php
include "./inner-inner.php";
In addition, and as mentioned in other comments, if you have configured a different "load path" for your PHP application, that load path will be looked up first without the ./ syntax. Instead, the ./ syntax is more efficient because it doesn't check the "include path" of php 1.
If you wanna make your includes even more explicit, use the __DIR__ constant. This tells php: "Use the directory of this file" 2.
# src/inner.php
<?php
include __DIR__ . "/inner-inner.php";
TLDR; Always use ./ or __DIR__ 2 because it's relative to the current (working) directory and doesn't depend on the PHP "include path" 1.
References:
[Include - https://www.php.net/manual/en/function.include.php]
Magic Constants - https://www.php.net/manual/en/language.constants.magic.php
Simply you are telling php to include the file in the current directory only or fail if the file is not present.
If you use the format "indexcommon3.php" and the file is not present php will search it into the include_path system variable.
For reference you can use http://www.php.net/manual/en/function.include.php
It's explicitly naming the current directory.
I was writing an web app in PHP, when I encountered a strange situation. To illustrate my problem, consider a web app of this structure:
/
index.php
f1/
f1.php
f2/
f2.php
Contents of these files:
index.php:
<?php require_once("f1/f1.php"); ?>
f1.php:
<?php require_once("../f2/f2.php"); ?>
f2.php: blank
now when I try to open index.php in my browser I get this error:
Warning: require_once(../f2/f2.php) [function.require-once]:
failed to open stream: No such file or directory in /var/www/reqtest/f1/f1.php on line 2
Fatal error: require_once() [function.require]:
Failed opening required '../f2/f2.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/reqtest/f1/f1.php on line 2
Is there something obvious I'm missing? how do include paths work in PHP?
Before I asked this question, I attempted to experiment and find out. I set up another test, like so:
/
index.php
f1/
f1.php
f2.php
index.php:
<?php require_once("f1/f1.php"); ?>
f1.php:
<?php require_once("f2.php"); ?>
f2.php: blank
To my surprise (and utter confusion), this worked out fine!
So, what is the secret behind the path resolution?
PS I saw this question, but it still does not answer the second case that I've stated here.
If you include another file, the working directory remains where the including file is.
Your examples are working as intended.
Edit: The second example works because . (actual directory) is in your include path (see your error message).
Edit2:
In your second example, the key point of your interest is this line:
<?php require_once("f2.php"); ?>
At first it will look in the current working dir (/var/www/req_path_test), but does not find f2.php.
As fallback, it will try to find f2.php in your include_path ('.:/usr/share/php:/usr/share/pear'), starting with '.' (which is relative to the actual file, not the including one).
So './f2.php' works and the require does not fail.
When you open index.php, working dir is set to the folder this file resides in. And inside insluded f1.php this working dir does not change.
You can include files by using their absolute paths, relative to the current included file like this:
require_once(dirname(__FILE__).'/../../test/file.php')
But better consider using an autoloader if these files contain classes.
Normaly in you old structure
<?php require_once("f2/f2.php"); ?>
instead of
<?php require_once("../f2/f2.php"); ?>
should work. As far as i know php takes the paths from the initial script
It sounds like your server has the open_basedir setting enabled in the PHP configuration. This makes it impossible to include (and open) files in folders above your in the directory structur (i.e., you can't use ../ to go up in the folder structure).
From the PHP Docs PHP include
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.
If the file path is not given then i.e require_once("f2.php");
1st. The include_path is checked
2nd. The calling scripts own directory is checked
3rd. Finally the current working directory is checked
If file not found then PHP throws warning on file include & fatal error on require
If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.
If you include/require your file beginning with . or .. or ./ then PHP's parser will look in the parent directory which is the current working directory i.e require_once("../f2/f2.php"), php will check at the root directory as the calling script index.php is in that directory.
Now You have not defined any include path in your PHP script thus it always falls back to the calling script and then into the current working directory.
// Check your default include path, most likely to be C:\xampp\php\PEAR
echo get_include_path();
// To set include path
set_include_path ( string $new_include_path ) : string
The Current Working Directory is derived from your main calling script index.php.
// The Current Working Directory can be checked
echo getcwd();
In the first Example where the required file "../f2/f2.php" is from f1.php
You code does not work because -
The specified path is ignored by PHP as your filename begins with ../
f1/ the calling script's own directory is ignored as well.
The parser directory looks into the parent directory to find the requested file. The current working directory is root directory, this is from where you have initiated the working script index.php. The file is not located at this directory, wrong path given.
Thus you get the Fatal Error
In the Second example you have changed the directory & from f1.php you require_once("f2.php").
Your code works because -
This time you require("f2.php") no leading ../ or ./ This time PHP checks the include_path but does find it there, as you haven't defined it and the file does not reside in the default preset include_path.
This time the calling script f1.php's directory is f1/. and you require file ("f2.php") is located at this directory. PHP This time checks the file in this directory and finds it.
PHP does not have to check the working directory as the file was found.
Thus Your Code Works Fine!
I'm having trouble understanding the ruleset regarding PHP relative include paths. If I run file A.PHP- and file A.PHP includes file B.PHP which includes file C.PHP, should the relative path to C.PHP be in relation to the location of B.PHP, or to the location of A.PHP? That is, does it matter which file the include is called from, or only what the current working directory is- and what determines the current working directory?
It's relative to the main script, in this case A.php. Remember that include() just inserts code into the currently running script.
That is, does it matter which file the include is called from
No.
If you want to make it matter, and do an include relative to B.php, use the __FILE__ constant (or __DIR__ since PHP 5.2 IIRC) which will always point to the literal current file that the line of code is located in.
include(dirname(__FILE__)."/C.PHP");
#Pekka got me there, but just want to share what I learned:
getcwd() returns the directory where the file you started executing resides.
dirname(__FILE__) returns the directory of the file containing the currently executing code.
Using these two functions, you can always build an include path relative to what you need.
e.g., if b.php and c.php share a directory, b.php can include c.php like:
include(dirname(__FILE__).'/c.php');
no matter where b.php was called from.
In fact, this is the preferred way of establishing relative paths, as the extra code frees PHP from having to iterate through the include_path in the attempt to locate the target file.
Sources:
Difference Between getcwd() and dirname(__FILE__) ? Which should I use?
Why you should use dirname(__FILE__)
The accepted answer of Pekka is incomplete and, in a general context, misleading. If the file is provided as a relative path, the called language construct include will search for it in the following way.
First, it will go through the paths of the environment variable include_path, which can be set with ini_set. If this fails, it will search in the calling script's own directory dirname(__FILE__) (__DIR__ with php >= 5.3.) If this also fails, only then it will search in the working directory ! It just turns out that, by default, the environment variable include_path begins with ., which is the current working directory. That is the only reason why it searches first in the current working directory. See http://php.net/manual/en/function.include.php.
Files are included based on the file path given or, if none is given,
the include_path specified. If the file isn't found in the
include_path, include will finally check in the calling script's own
directory and the current working directory before failing.
So, the correct answer to the first part of the question is that it does matter where is located the included calling script. The answer to the last part of the question is that the initial working directory, in a web server context, is the directory of the called script, the script that includes all the others while being handled by PHP. In a command line context, the initial working directory is whatever it is when php is invoked at the prompt, not necessarily the directory where the called script is located. The current working directory, however, can be changed at run time with the PHP function chdir. See http://php.net/manual/en/function.chdir.php.
This paragraph is added to comment on other answers. Some have mentioned that relying on include_path is less robust and thus it is preferable to use full paths such as ./path or __DIR__ . /path. Some went as far as saying that relying on the working directory . itself is not safe, because it can be changed. However, some times, you need to rely on environment values. For example, you might want set include_path empty, so that the directory of the calling script is the first place that it will search, even before the current working directory. The code might be already written and updated regularly from external sources and you do not want to reinsert the prefix __DIR__ each time the code is updated.
If include path doesn't start with ./ or ../, e.g.:
include 'C.php'; // precedence: include_path (which include '.' at first),
// then path of current `.php` file (i.e. `B.php`), then `.`.
If include path starts with ./ or ../, e.g.:
include './C.php'; // relative to '.'
include '../C.php'; // also relative to '.'
The . or .. above is relative to getcwd(), which defaults to the path of the entry .php file (i.e. A.php).
Tested on PHP 5.4.3 (Build Date : May 8 2012 00:47:34).
(Also note that chdir() can change the output of getcwd().)
Short answer: it's relative to the including script.
TFM explains it correctly:
If the file isn't found in the include_path, include will check in the calling script's directory and the current working directory
So, if /app/main.php says include("./inc.php") that will find /app/inc.php.
The ./ is not strictly necessary but removes any dependency on include_path.
I would not rely on finding include files in the current working directory in case someone changes it with chdir().
dir
-> a.php
-> c.php
- dir2
-> b.php
To include a in b you need to include("../a.php");
To include b in c you need to include("dir2/b.php");
When I use ../mysqlConnect.php I get the following messages.
Warning: require_once(../mysqlConnect.php) [function.require-once]:
failed to open stream: No such file or directory in /home/content/etc...
Fatal error: require_once() [function.require]: Failed opening required
'../mysqlConnect.php' (include_path='.:/usr/local/php5/lib/php') in /home/content/etc...
When I use the directory name - mydir/mysqlConnect.php - everything works fine.
require_once('../mysqlConnect.php') asks PHP to look in the directory above the one your script is currently in for mysqlConnect.php.
Since your connection file appears to be in a mydir directory, require_once('mydir/mysqlConnect.php') works because it looks in that directory, which is contained by the one it's currently in.
Visual representation (assuming script.php is your script including that file):
dir/
subdir/ # PHP looks here for ../mysqlConnect.php
script.php
mydir/ # PHP looks here for mydir/mysqlConnect.php
mysqlConnect.php
Require is relative to the invoced script, not the script you call require() in. Use something like this to have an absolute path:
require(dirname(__FILE__) . '/../mysqlConnect.php');
In PHP 5 you can also use DIR.
because it doesn't find your file then. to give a more specific answer I need to see you file-/folder-structure
That's because you are not specifying the correct include path. ../ refers to parent directory. ../../ goes two directories back, ../../../ goes three of them back. If the mysqlConnect.php file is present in the same folder as your script, you don't need to specify ../ in the include.
Make sure that you specify the correct path. You can easily check whether or not you are specifying correct path like:
if (file_exists('../mysqlConnect.php'))
{
echo 'Iam specifying the correct path !!';
}
else
{
echo 'Well, I am not :(';
}
I was writing an web app in PHP, when I encountered a strange situation. To illustrate my problem, consider a web app of this structure:
/
index.php
f1/
f1.php
f2/
f2.php
Contents of these files:
index.php:
<?php require_once("f1/f1.php"); ?>
f1.php:
<?php require_once("../f2/f2.php"); ?>
f2.php: blank
now when I try to open index.php in my browser I get this error:
Warning: require_once(../f2/f2.php) [function.require-once]:
failed to open stream: No such file or directory in /var/www/reqtest/f1/f1.php on line 2
Fatal error: require_once() [function.require]:
Failed opening required '../f2/f2.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/reqtest/f1/f1.php on line 2
Is there something obvious I'm missing? how do include paths work in PHP?
Before I asked this question, I attempted to experiment and find out. I set up another test, like so:
/
index.php
f1/
f1.php
f2.php
index.php:
<?php require_once("f1/f1.php"); ?>
f1.php:
<?php require_once("f2.php"); ?>
f2.php: blank
To my surprise (and utter confusion), this worked out fine!
So, what is the secret behind the path resolution?
PS I saw this question, but it still does not answer the second case that I've stated here.
If you include another file, the working directory remains where the including file is.
Your examples are working as intended.
Edit: The second example works because . (actual directory) is in your include path (see your error message).
Edit2:
In your second example, the key point of your interest is this line:
<?php require_once("f2.php"); ?>
At first it will look in the current working dir (/var/www/req_path_test), but does not find f2.php.
As fallback, it will try to find f2.php in your include_path ('.:/usr/share/php:/usr/share/pear'), starting with '.' (which is relative to the actual file, not the including one).
So './f2.php' works and the require does not fail.
When you open index.php, working dir is set to the folder this file resides in. And inside insluded f1.php this working dir does not change.
You can include files by using their absolute paths, relative to the current included file like this:
require_once(dirname(__FILE__).'/../../test/file.php')
But better consider using an autoloader if these files contain classes.
Normaly in you old structure
<?php require_once("f2/f2.php"); ?>
instead of
<?php require_once("../f2/f2.php"); ?>
should work. As far as i know php takes the paths from the initial script
It sounds like your server has the open_basedir setting enabled in the PHP configuration. This makes it impossible to include (and open) files in folders above your in the directory structur (i.e., you can't use ../ to go up in the folder structure).
From the PHP Docs PHP include
Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.
If the file path is not given then i.e require_once("f2.php");
1st. The include_path is checked
2nd. The calling scripts own directory is checked
3rd. Finally the current working directory is checked
If file not found then PHP throws warning on file include & fatal error on require
If a path is defined — whether absolute (starting with a drive letter or \ on Windows, or / on Unix/Linux systems) or relative to the current directory (starting with . or ..) — the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.
If you include/require your file beginning with . or .. or ./ then PHP's parser will look in the parent directory which is the current working directory i.e require_once("../f2/f2.php"), php will check at the root directory as the calling script index.php is in that directory.
Now You have not defined any include path in your PHP script thus it always falls back to the calling script and then into the current working directory.
// Check your default include path, most likely to be C:\xampp\php\PEAR
echo get_include_path();
// To set include path
set_include_path ( string $new_include_path ) : string
The Current Working Directory is derived from your main calling script index.php.
// The Current Working Directory can be checked
echo getcwd();
In the first Example where the required file "../f2/f2.php" is from f1.php
You code does not work because -
The specified path is ignored by PHP as your filename begins with ../
f1/ the calling script's own directory is ignored as well.
The parser directory looks into the parent directory to find the requested file. The current working directory is root directory, this is from where you have initiated the working script index.php. The file is not located at this directory, wrong path given.
Thus you get the Fatal Error
In the Second example you have changed the directory & from f1.php you require_once("f2.php").
Your code works because -
This time you require("f2.php") no leading ../ or ./ This time PHP checks the include_path but does find it there, as you haven't defined it and the file does not reside in the default preset include_path.
This time the calling script f1.php's directory is f1/. and you require file ("f2.php") is located at this directory. PHP This time checks the file in this directory and finds it.
PHP does not have to check the working directory as the file was found.
Thus Your Code Works Fine!