I have this condition :
a file : /public_html/folderX/test.php has a line : require_once '../functions/sendemail.php'
on the other hand, /public_html/functions/sendemail.php has a line : require_once '../config.php'
config.php loads perfectly in this situation.
the problem occurs when I try to add that functions/sendemail.php on file(s) which not in the folderX, for example :
when I tried to add require_once 'functions/sendemail.php' on public_html/test.php I got this error message :
Warning: require_once(../config-min.php) [function.require-once]: failed to open stream: No such file or directory in public_html/test.php
how to make require_once '../config.php' inside functions/sendemail.php works 'independently' so wherever it's included on any files this 'require_once' problem won't occur anymore.
I tried to change into 'include_once' but still doesn't work.
thanks!
try something like
require_once( dirname(__FILE__).'/../config.php')
Try using __DIR__ to attain the current path of the script.
require_once(__DIR__.'../config.php');
__DIR__ only works on php 5.3
__DIR__
The directory of the file. If used inside an include, the directory of
the included file is returned. This is equivalent to dirname(__FILE__).
This directory name does not have a trailing slash unless it is the root directory.
(Added in PHP 5.3.0.)
I believe the relative path names are biting you here. Relative paths are (to my knowledge) based on the directory of the currently active script. PHP doesn't chdir into a folder when including or requiring files. The best recommendation (in my limited experience) for this kind of thing is to use absolute paths where possible. So something like:
require_once('../config.php');
would become:
require_once('/home/myuser/config.php'); // Or wherever the file really is
The dirname function can help in this situation.
You must understand that PHP changes directory to that of the outermost script. When you use relative paths (e.g. those that begin with ./, ../, or those that do not begin with /), PHP will use the current directory to resolve the relative paths. This causes problem when you copy-paste the include lines in your code. Consider this directory structure:
/index.php
/admin/index.php
/lib/include.php
Assume the two index files contain these lines:
include_once("lib/include.php");
The above line will work when /index.php is called but not when /admin/index.php is called.
The solution is to not copy-paste code, use correct relative file paths in your include calls:
/index.php -> include_once("lib/include.php");
/admin/index.php -> include_once("../lib/include.php");
Related
I have file /root/update/test.php. There's also a file, /root/connect.php; This file has a line
include "../config.php";
In /root/update/test.php. There's the code
set_include_path(".:/root");
include "connect.php";
When I run /root/update/test.php, it finds connect.php, but fails to find config.php, giving me
PHP Warning: include(../config.php): failed to open stream: No such file or directory in /root/connect.php on line 2
PHP Warning: include(): Failed opening '../config.php' for inclusion (include_path='.:/root')
This is confusing to me because the warnings make it seem like I'm doing everything correctly - the include path is /root, and it's looking for file ../config.php (/config.php), which exists. Can someone clear this up for me? Note that using absolute paths is not an option for me, due to deploying to a production server that I have no access to.
Ubuntu/Apache
You could always include it using __DIR__:
include(dirname(__DIR__).'/config.php');
__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.
You could set the root path in this method too:
define('ROOT_PATH', dirname(__DIR__) . '/');
in test.php would set your root to be at the /root/ level.
include(ROOT_PATH.'config.php');
Should then work to include the config file from where you want.
While I appreciate you believe absolute paths is not an option, it is a better option than relative paths and updating the PHP include path.
Use absolute paths with an constant you can set based on environment.
if (is_production()) {
define('ROOT_PATH', '/some/production/path');
}
else {
define('ROOT_PATH', '/root');
}
include ROOT_PATH . '/connect.php';
As commented, ROOT_PATH could also be derived from the current path, $_SERVER['DOCUMENT_ROOT'], etc.
I have file /root/update/test.php. There's also a file, /root/connect.php; This file has a line
include "../config.php";
In /root/update/test.php. There's the code
set_include_path(".:/root");
include "connect.php";
When I run /root/update/test.php, it finds connect.php, but fails to find config.php, giving me
PHP Warning: include(../config.php): failed to open stream: No such file or directory in /root/connect.php on line 2
PHP Warning: include(): Failed opening '../config.php' for inclusion (include_path='.:/root')
This is confusing to me because the warnings make it seem like I'm doing everything correctly - the include path is /root, and it's looking for file ../config.php (/config.php), which exists. Can someone clear this up for me? Note that using absolute paths is not an option for me, due to deploying to a production server that I have no access to.
Ubuntu/Apache
You could always include it using __DIR__:
include(dirname(__DIR__).'/config.php');
__DIR__ is a 'magical constant' and returns the directory of the current file without the trailing slash. It's actually an absolute path, you just have to concatenate the file name to __DIR__. In this case, as we need to ascend a directory we use PHP's dirname which ascends the file tree, and from here we can access config.php.
You could set the root path in this method too:
define('ROOT_PATH', dirname(__DIR__) . '/');
in test.php would set your root to be at the /root/ level.
include(ROOT_PATH.'config.php');
Should then work to include the config file from where you want.
While I appreciate you believe absolute paths is not an option, it is a better option than relative paths and updating the PHP include path.
Use absolute paths with an constant you can set based on environment.
if (is_production()) {
define('ROOT_PATH', '/some/production/path');
}
else {
define('ROOT_PATH', '/root');
}
include ROOT_PATH . '/connect.php';
As commented, ROOT_PATH could also be derived from the current path, $_SERVER['DOCUMENT_ROOT'], etc.
I work with PHP on Windows, sience a few days. The whole time I've been indicated include in the following manner:
In index.php file:
require ('include/init.inc');
In the directory "include" I stated:
In init.inc file:
require ("workbench.inc");
But suddenly no longer works. At one time I must also in "init.inc" specify the directory.
Why did it all the time to work, and suddenly no more?
From the PHP documentation:
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 current working directory (CWD) is important when including other files. It can be retrieved by getcwd().
If your directory structure looks like this
rootdir/
include/
init.rc
workbench.rc
index.php
then a require('include/init.rc') will only work if rootdir/ is the CWD or is part of the search path. Likewise, require('init.inc') assumes the CWD is rootdir/include/. Since the current working directory can change, it is idomatic in PHP to use the more robust
// in index.php
require(__DIR__ . '/include/init.rc');
// in workbench.rc
require(__DIR__ . '/init.rc');
Then the require will work independent of the CWD. This works because the magic constant __DIR__ is replaced by the absolute path to the file that contains the constant without a trailing directory separator, for example
in index.php, __DIR__ is D:\path\to\rootdir and
in include/init.rc, __DIR__ is D:\path\to\rootdir\include.
I have a file that is called header (the header of my site).. I use that file in all my site. The problem is that it has this include in it:
include_once("../untitled/sanitize_string.php");
which means that a mistake may be thrown, depending on who calls the header file.
I have directories, subdirectories and subdirectories to the subdirectories.. is there a simple way to prevent this from happening.. Instead of taking the satize string include and placing it on every page and not in the header file
Warning: require_once(/untitled/sanitize_string.php) [function.require-once]: failed to open stream: No such file or directory in C:\xampp\htdocs\PoliticalForum\StoredProcedure\User\headerSite.php on line 7
Fatal error: require_once() [function.require]: Failed opening required '/untitled/sanitize_string.php' (include_path='.;C:\xampp\php\PEAR') in C:\xampp\htdocs\PoliticalForum\StoredProcedure\User\headerSite.php on line 7
You may consider setting a global include path while using include.
For php 5.3 you can do:
include_once(__DIR__ . '/../untitled/sanitize_string.php');
where __DIR__ is the directory for the current file
For older versions you can use
include_once(dirname(__FILE__) . '/../untitled/sanitize_string.php');
where __FILE__ is the path for the current file
Lets say you have the following structure:
/app/path/public/header.php
/app/path/public/user/profile.php
/app/path/untitled/sanitize_string.php
If your header.php includes santitize_script.php with a relative path like so:
include_once("../untitled/sanitize_string.php");
the php interpreter will try to include that file RELATIVELY to the current working dir so if you will do a request like http://localhost/header.php it will try to include it from /app/path/public/../untitled/sanitize_string.php and it will work.
But if you will try to do a request like http://localhost/user/profile.php and profile.php includes header.php, than header.php will try to include the file from /app/path/public/user/../untitled/sanitize_string.php and this will not work anymore. (/app/path/public/user beeing the current working dir now)
That's why is a good practice to use absolute paths when including files. When used in header.php, the __DIR__ and __FILE__ constants will always have the same values: /app/path/public and /app/path/public/header.php respectively no matter where header.php will be used thereafter
Use absolute path...
include_once('/home/you/www/include.php');
Use absolute path as yes123 said.
include_once(dirname(__FILE__)."/../untitled/sanitize_string.php");
You're going to have to use absolute paths here, as opposed to relative. I often set up some constants to represent important directories, using the old Server vars. Like so:
define('MY_DIR',$_SERVER['DOCUMENT_ROOT'].'/path/to/yer/dir');
Then, modify your include statement:
include_once(MY_DIR.'/your_file.php');
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!