I have a couple files that look like this:
index.php:
<?php
include('includes/header.php');
...
includes/header.php:
<?php
include('config.php');
...
The error I get is
Warning: require(config.php) [function.require]: failed to open stream: No such file or directory in [dir]/includes/header.php on line 2
Fatal error: require() [function.require]: Failed opening required 'config.php' (include_path='.:/usr/share/pear:/usr/share/php') in [dir]/includes/header.php on line 2
I did some further debugging: when I add the call
system('pwd');
to includes/header.php, it shows [dir], where it should say [dir]/includes. Adding the 'includes/' to the include path works, but isn't desirable because that would fail on the production server.
The above code works on a production server, and worked fine on my development Fedora server, until I tried to change my development environment so that the Fedora server's document root is a mounted CIFS share.
Any ideas? Thanks.
worked fine ... until I tried to change my development environment so that the Fedora server's document root is a mounted CIFS share.
Is SELinux enabled?
Check /var/log/audit/audit.log
I'm going to wager that SELinux is enabled and in enforcing mode, and is interfering.
I hate to say it, but the behavior with pwd that you're describing is 100% expected behavior (and has been since at least PHP4... probably earlier).
PHP automatically sets the current working directory (used by pwd) ONCE. PHP does not change it. Thus, . will refer to the original current working directory unless you manually change it with chdir().
There are various solutions to this problem used; most of which you can see at PHP include file strategy needed.
If it worked before, there was probably some updating of the include_path somewhere, code that changed the the working directory no longer changes it, or the php version you used that implemented this odd (but more expected) behavior no longer does so.
Anyways, I'd check the include paths: ini files, or scripts that change the include path. I'm guessing something used to update the include_path, but no longer does so.
I'm not sure about the details of how you moved it but I've encountered some annoying scripts where an .htaccess set an auto_prepend_file to a hardcoded path to a file completely outside the website structure, that set the include path (among other things) to somewhere inside the web structure.
Mounting the CIFS share with the option 'noserverino' should resolve the issue, for example:
mount -t cifs -o noserverino //host/share /mnt
Full explanation of why this works can be found here: http://www.php.net//manual/en/function.is-dir.php#98338
Related
In PHP scripts, whether calling include(), require(), fopen(), or their derivatives such as include_once, require_once, or even, move_uploaded_file(), one often runs into an error or warning:
Failed to open stream : No such file or directory.
What is a good process to quickly find the root cause of the problem?
There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.
Let's consider that we are troubleshooting the following line:
require "/path/to/file"
Checklist
1. Check the file path for typos
either check manually (by visually checking the path)
or move whatever is called by require* or include* to its own variable, echo it, copy it, and try accessing it from a terminal:
$path = "/path/to/file";
echo "Path : $path";
require "$path";
Then, in a terminal:
cat <file path pasted>
2. Check that the file path is correct regarding relative vs absolute path considerations
if it is starting by a forward slash "/" then it is not referring to the root of your website's folder (the document root), but to the root of your server.
for example, your website's directory might be /users/tony/htdocs
if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the current working directory.
thus, not relative to the path of your web site's root, or to the file where you are typing
for that reason, always use absolute file paths
Best practices :
In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :
use require __DIR__ . "/relative/path/from/current/file". The __DIR__ magic constant returns the directory of the current file.
define a SITE_ROOT constant yourself :
at the root of your web site's directory, create a file, e.g. config.php
in config.php, write
define('SITE_ROOT', __DIR__);
in every file where you want to reference the site root folder, include config.php, and then use the SITE_ROOT constant wherever you like :
require_once __DIR__."/../config.php";
...
require_once SITE_ROOT."/other/file.php";
These 2 practices also make your application more portable because it does not rely on ini settings like the include path.
3. Check your include path
Another way to include files, neither relatively nor purely absolutely, is to rely on the include path. This is often the case for libraries or frameworks such as the Zend framework.
Such an inclusion will look like this :
include "Zend/Mail/Protocol/Imap.php"
In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.
You can check the include path with :
echo get_include_path();
You can add a folder to it with :
set_include_path(get_include_path().":"."/path/to/new/folder");
4. Check that your server has access to that file
It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.
To check under what user the server is running you can use posix_getpwuid :
$user = posix_getpwuid(posix_geteuid());
var_dump($user);
To find out the permissions on the file, type the following command in the terminal:
ls -l <path/to/file>
and look at permission symbolic notation
5. Check PHP settings
If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.
Three settings could be relevant :
open_basedir
If this is set PHP won't be able to access any file outside of the specified directory (not even through a symbolic link).
However, the default behavior is for it not to be set in which case there is no restriction
This can be checked by either calling phpinfo() or by using ini_get("open_basedir")
You can change the setting either by editing your php.ini file or your httpd.conf file
safe mode
if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is still being supported.
allow_url_fopen and allow_url_include
this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system
this can be checked with ini_get("allow_url_include") and set with ini_set("allow_url_include", "1")
Corner cases
If none of the above enabled to diagnose the problem, here are some special situations that could happen :
1. The inclusion of library relying on the include path
It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :
require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php"
But then you still get the same kind of error.
This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.
For example, the Zend framework file mentioned before could have the following include :
include "Zend/Mail/Protocol/Exception.php"
which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.
In such a case, the only practical solution is to add the directory to your include path.
2. SELinux
If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.
To check whether SELinux is enabled on your system, run the sestatus command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.
To check whether SELinux policies are the reason for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.
setenforce 0
If you no longer have the problem with SELinux turned off, then this is the root cause.
To solve it, you will have to configure SELinux accordingly.
The following context types will be necessary :
httpd_sys_content_t for files that you want your server to be able to read
httpd_sys_rw_content_t for files on which you want read and write access
httpd_log_t for log files
httpd_cache_t for the cache directory
For example, to assign the httpd_sys_content_t context type to your website root directory, run :
semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?"
restorecon -Rv /path/to/root
If your file is in a home directory, you will also need to turn on the httpd_enable_homedirs boolean :
setsebool -P httpd_enable_homedirs 1
In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. Here is a tutorial specifically on configuring SELinux for a web server.
3. Symfony
If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because app/cache has been uploaded, or that cache hasn't been cleared.
You can test and fix this by running the following console command:
cache:clear
4. Non ACSII characters inside Zip file
Apparently, this error can happen also upon calling zip->close() when some files inside the zip have non-ASCII characters in their filename, such as "é".
A potential solution is to wrap the file name in utf8_decode() before creating the target file.
Credits to Fran Cano for identifying and suggesting a solution to this issue
To add to the (really good) existing answer
Shared Hosting Software
open_basedir is one that can stump you because it can be specified in a web server configuration. While this is easily remedied if you run your own dedicated server, there are some shared hosting software packages out there (like Plesk, cPanel, etc) that will configure a configuration directive on a per-domain basis. Because the software builds the configuration file (i.e. httpd.conf) you cannot change that file directly because the hosting software will just overwrite it when it restarts.
With Plesk, they provide a place to override the provided httpd.conf called vhost.conf. Only the server admin can write this file. The configuration for Apache looks something like this
<Directory /var/www/vhosts/domain.com>
<IfModule mod_php5.c>
php_admin_flag engine on
php_admin_flag safe_mode off
php_admin_value open_basedir "/var/www/vhosts/domain.com:/tmp:/usr/share/pear:/local/PEAR"
</IfModule>
</Directory>
Have your server admin consult the manual for the hosting and web server software they use.
File Permissions
It's important to note that executing a file through your web server is very different from a command line or cron job execution. The big difference is that your web server has its own user and permissions. For security reasons that user is pretty restricted. Apache, for instance, is often apache, www-data or httpd (depending on your server). A cron job or CLI execution has whatever permissions that the user running it has (i.e. running a PHP script as root will execute with permissions of root).
A lot of times people will solve a permissions problem by doing the following (Linux example)
chmod 777 /path/to/file
This is not a smart idea, because the file or directory is now world writable. If you own the server and are the only user then this isn't such a big deal, but if you're on a shared hosting environment you've just given everyone on your server access.
What you need to do is determine the user(s) that need access and give only those them access. Once you know which users need access you'll want to make sure that
That user owns the file and possibly the parent directory (especially the parent directory if you want to write files). In most shared hosting environments this won't be an issue, because your user should own all the files underneath your root. A Linux example is shown below
chown apache:apache /path/to/file
The user, and only that user, has access. In Linux, a good practice would be chmod 600 (only owner can read and write) or chmod 644 (owner can write but everyone can read)
You can read a more extended discussion of Linux/Unix permissions and users here
Look at the exact error
My code worked fine on all machines but only on this one started giving problem (which used to work find I guess). Used echo "document_root" path to debug and also looked closely at the error, found this
Warning:
include(D:/MyProjects/testproject//functions/connections.php):
failed to open stream:
You can easily see where the problems are. The problems are // before functions
$document_root = $_SERVER['DOCUMENT_ROOT'];
echo "root: $document_root";
include($document_root.'/functions/connections.php');
So simply remove the lading / from include and it should work fine. What is interesting is this behaviors is different on different versions. I run the same code on Laptop, Macbook Pro and this PC, all worked fine untill. Hope this helps someone.
Copy past the file location in the browser to make sure file exists. Sometimes files get deleted unexpectedly (happened with me) and it was also the issue in my case.
Samba Shares
If you have a Linux test server and you work from a Windows Client, the Samba share interferes with the chmod command. So, even if you use:
chmod -R 777 myfolder
on the Linux side it is fully possible that the Unix Group\www-data still doesn't have write access. One working solution if your share is set up that Windows admins are mapped to root: From Windows, open the Permissions, disable Inheritance for your folder with copy, and then grant full access for www-data.
Add script with query parameters
That was my case. It actually links to question #4485874, but I'm going to explain it here shortly.
When you try to require path/to/script.php?parameter=value, PHP looks for file named script.php?parameter=value, because UNIX allows you to have paths like this.
If you are really need to pass some data to included script, just declare it as $variable=... or $GLOBALS[]=... or other way you like.
Aside from the other excellent answers, one thing I overlooked on Windows while writing a simple script: This error will be shown when trying to open a file with characters that Windows does not support in file names.
For example:
$file = fopen(date('Y-m-d_H:i:s'), 'w+');
Will give:
fopen(2022-06-01_22:53:03): Failed to open stream: No such file or directory in ...
Windows does not like : in file names, as well as a number of other characters.
The following PHP settings in php.ini if set to non-existent directory can also raise
PHP Warning: Unknown: failed to open stream: Permission denied in
Unknown on line 0
sys_temp_dir
upload_tmp_dir
session.save_path
PHP - Failed to open stream : No such file or directory in mac
For example I will upload a picture. But I am getting this error. First thing i will do right click on the image and get info.
$thePathOfMyPicture = "/Users/misstugba/Desktop/";
use with function
if(move_uploaded_file($_FILES["file"]["tmp_name"],$thePathOfMyPicture.$_FILES["file"]["name"])){
echo "image uploaded successfully";
}
For me I got this error because I was trying to read a file which required HTTP auth, with a username and password. Hope that helps others. Might be another corner case.
Edit
You can check if this type of authentication is present by inspecting the headers:
$file_headers = get_headers($url);
if (!$file_headers) echo 'File headers missing';
else if (strpos($file_headers[0], '401 Unauthorized') > -1) echo '401 Unauthorized';
In PHP, start Apache then write you DB name and password if exist in your environment(.env).
In PHP scripts, whether calling include(), require(), fopen(), or their derivatives such as include_once, require_once, or even, move_uploaded_file(), one often runs into an error or warning:
Failed to open stream : No such file or directory.
What is a good process to quickly find the root cause of the problem?
There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.
Let's consider that we are troubleshooting the following line:
require "/path/to/file"
Checklist
1. Check the file path for typos
either check manually (by visually checking the path)
or move whatever is called by require* or include* to its own variable, echo it, copy it, and try accessing it from a terminal:
$path = "/path/to/file";
echo "Path : $path";
require "$path";
Then, in a terminal:
cat <file path pasted>
2. Check that the file path is correct regarding relative vs absolute path considerations
if it is starting by a forward slash "/" then it is not referring to the root of your website's folder (the document root), but to the root of your server.
for example, your website's directory might be /users/tony/htdocs
if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the current working directory.
thus, not relative to the path of your web site's root, or to the file where you are typing
for that reason, always use absolute file paths
Best practices :
In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :
use require __DIR__ . "/relative/path/from/current/file". The __DIR__ magic constant returns the directory of the current file.
define a SITE_ROOT constant yourself :
at the root of your web site's directory, create a file, e.g. config.php
in config.php, write
define('SITE_ROOT', __DIR__);
in every file where you want to reference the site root folder, include config.php, and then use the SITE_ROOT constant wherever you like :
require_once __DIR__."/../config.php";
...
require_once SITE_ROOT."/other/file.php";
These 2 practices also make your application more portable because it does not rely on ini settings like the include path.
3. Check your include path
Another way to include files, neither relatively nor purely absolutely, is to rely on the include path. This is often the case for libraries or frameworks such as the Zend framework.
Such an inclusion will look like this :
include "Zend/Mail/Protocol/Imap.php"
In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.
You can check the include path with :
echo get_include_path();
You can add a folder to it with :
set_include_path(get_include_path().":"."/path/to/new/folder");
4. Check that your server has access to that file
It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.
To check under what user the server is running you can use posix_getpwuid :
$user = posix_getpwuid(posix_geteuid());
var_dump($user);
To find out the permissions on the file, type the following command in the terminal:
ls -l <path/to/file>
and look at permission symbolic notation
5. Check PHP settings
If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.
Three settings could be relevant :
open_basedir
If this is set PHP won't be able to access any file outside of the specified directory (not even through a symbolic link).
However, the default behavior is for it not to be set in which case there is no restriction
This can be checked by either calling phpinfo() or by using ini_get("open_basedir")
You can change the setting either by editing your php.ini file or your httpd.conf file
safe mode
if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is still being supported.
allow_url_fopen and allow_url_include
this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system
this can be checked with ini_get("allow_url_include") and set with ini_set("allow_url_include", "1")
Corner cases
If none of the above enabled to diagnose the problem, here are some special situations that could happen :
1. The inclusion of library relying on the include path
It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :
require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php"
But then you still get the same kind of error.
This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.
For example, the Zend framework file mentioned before could have the following include :
include "Zend/Mail/Protocol/Exception.php"
which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.
In such a case, the only practical solution is to add the directory to your include path.
2. SELinux
If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.
To check whether SELinux is enabled on your system, run the sestatus command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.
To check whether SELinux policies are the reason for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.
setenforce 0
If you no longer have the problem with SELinux turned off, then this is the root cause.
To solve it, you will have to configure SELinux accordingly.
The following context types will be necessary :
httpd_sys_content_t for files that you want your server to be able to read
httpd_sys_rw_content_t for files on which you want read and write access
httpd_log_t for log files
httpd_cache_t for the cache directory
For example, to assign the httpd_sys_content_t context type to your website root directory, run :
semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?"
restorecon -Rv /path/to/root
If your file is in a home directory, you will also need to turn on the httpd_enable_homedirs boolean :
setsebool -P httpd_enable_homedirs 1
In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. Here is a tutorial specifically on configuring SELinux for a web server.
3. Symfony
If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because app/cache has been uploaded, or that cache hasn't been cleared.
You can test and fix this by running the following console command:
cache:clear
4. Non ACSII characters inside Zip file
Apparently, this error can happen also upon calling zip->close() when some files inside the zip have non-ASCII characters in their filename, such as "é".
A potential solution is to wrap the file name in utf8_decode() before creating the target file.
Credits to Fran Cano for identifying and suggesting a solution to this issue
To add to the (really good) existing answer
Shared Hosting Software
open_basedir is one that can stump you because it can be specified in a web server configuration. While this is easily remedied if you run your own dedicated server, there are some shared hosting software packages out there (like Plesk, cPanel, etc) that will configure a configuration directive on a per-domain basis. Because the software builds the configuration file (i.e. httpd.conf) you cannot change that file directly because the hosting software will just overwrite it when it restarts.
With Plesk, they provide a place to override the provided httpd.conf called vhost.conf. Only the server admin can write this file. The configuration for Apache looks something like this
<Directory /var/www/vhosts/domain.com>
<IfModule mod_php5.c>
php_admin_flag engine on
php_admin_flag safe_mode off
php_admin_value open_basedir "/var/www/vhosts/domain.com:/tmp:/usr/share/pear:/local/PEAR"
</IfModule>
</Directory>
Have your server admin consult the manual for the hosting and web server software they use.
File Permissions
It's important to note that executing a file through your web server is very different from a command line or cron job execution. The big difference is that your web server has its own user and permissions. For security reasons that user is pretty restricted. Apache, for instance, is often apache, www-data or httpd (depending on your server). A cron job or CLI execution has whatever permissions that the user running it has (i.e. running a PHP script as root will execute with permissions of root).
A lot of times people will solve a permissions problem by doing the following (Linux example)
chmod 777 /path/to/file
This is not a smart idea, because the file or directory is now world writable. If you own the server and are the only user then this isn't such a big deal, but if you're on a shared hosting environment you've just given everyone on your server access.
What you need to do is determine the user(s) that need access and give only those them access. Once you know which users need access you'll want to make sure that
That user owns the file and possibly the parent directory (especially the parent directory if you want to write files). In most shared hosting environments this won't be an issue, because your user should own all the files underneath your root. A Linux example is shown below
chown apache:apache /path/to/file
The user, and only that user, has access. In Linux, a good practice would be chmod 600 (only owner can read and write) or chmod 644 (owner can write but everyone can read)
You can read a more extended discussion of Linux/Unix permissions and users here
Look at the exact error
My code worked fine on all machines but only on this one started giving problem (which used to work find I guess). Used echo "document_root" path to debug and also looked closely at the error, found this
Warning:
include(D:/MyProjects/testproject//functions/connections.php):
failed to open stream:
You can easily see where the problems are. The problems are // before functions
$document_root = $_SERVER['DOCUMENT_ROOT'];
echo "root: $document_root";
include($document_root.'/functions/connections.php');
So simply remove the lading / from include and it should work fine. What is interesting is this behaviors is different on different versions. I run the same code on Laptop, Macbook Pro and this PC, all worked fine untill. Hope this helps someone.
Copy past the file location in the browser to make sure file exists. Sometimes files get deleted unexpectedly (happened with me) and it was also the issue in my case.
Samba Shares
If you have a Linux test server and you work from a Windows Client, the Samba share interferes with the chmod command. So, even if you use:
chmod -R 777 myfolder
on the Linux side it is fully possible that the Unix Group\www-data still doesn't have write access. One working solution if your share is set up that Windows admins are mapped to root: From Windows, open the Permissions, disable Inheritance for your folder with copy, and then grant full access for www-data.
Add script with query parameters
That was my case. It actually links to question #4485874, but I'm going to explain it here shortly.
When you try to require path/to/script.php?parameter=value, PHP looks for file named script.php?parameter=value, because UNIX allows you to have paths like this.
If you are really need to pass some data to included script, just declare it as $variable=... or $GLOBALS[]=... or other way you like.
Aside from the other excellent answers, one thing I overlooked on Windows while writing a simple script: This error will be shown when trying to open a file with characters that Windows does not support in file names.
For example:
$file = fopen(date('Y-m-d_H:i:s'), 'w+');
Will give:
fopen(2022-06-01_22:53:03): Failed to open stream: No such file or directory in ...
Windows does not like : in file names, as well as a number of other characters.
The following PHP settings in php.ini if set to non-existent directory can also raise
PHP Warning: Unknown: failed to open stream: Permission denied in
Unknown on line 0
sys_temp_dir
upload_tmp_dir
session.save_path
PHP - Failed to open stream : No such file or directory in mac
For example I will upload a picture. But I am getting this error. First thing i will do right click on the image and get info.
$thePathOfMyPicture = "/Users/misstugba/Desktop/";
use with function
if(move_uploaded_file($_FILES["file"]["tmp_name"],$thePathOfMyPicture.$_FILES["file"]["name"])){
echo "image uploaded successfully";
}
For me I got this error because I was trying to read a file which required HTTP auth, with a username and password. Hope that helps others. Might be another corner case.
Edit
You can check if this type of authentication is present by inspecting the headers:
$file_headers = get_headers($url);
if (!$file_headers) echo 'File headers missing';
else if (strpos($file_headers[0], '401 Unauthorized') > -1) echo '401 Unauthorized';
In PHP, start Apache then write you DB name and password if exist in your environment(.env).
I thought php include path was a pretty simple concept. I've done it many times, but now am having trouble getting it to work.
I am running an
centos 7.1 server on azure with Apache/2.4.6 PHP/5.4.16
When I modify the include_path within php.ini. The error after restarting apache shows
Failed opening required 'xfile' (include_path='.:/var/custom_directory')...
The include path is in the proper file format.
I might have an ownership problem.
I can place my files inside the default usr/share/php directory and the pages "include". However when I try to put my own directory inside of /var they do not.
I have done this before so I do not know why it isn't working now.
I have chowned and chmod these directories and their contents to death. Even mimicing the server that works's directories. Switching ownership to apache and giving full grant access just trying to get it to see the file from my /var/www/html/index.php
Am I missing something?
Is there something I need to enable or grant access or modify in the php or http.conf files?
Further information:
This is the only php.ini file included in the system /etc/php.ini
The purpose of the include path is to provide coding / user files behind the firewall.
I don't think this maters, but my vm is in Azure.
Putting something like this
include('/var/custom_directory/file.php');
Doesn't work as well. Why?
The include_path ini setting sets the path, it doesn't add to it, so if you change it you most likely mean to add an extra path, e.g.:
include_path = ".:/usr/share/php:/var/custom_directory"
This ensures that both your own custom_directory and the standard /usr/share/php directory are in the path.
(N.B. On Linux the path seperator is a colon (:), on Windows it is a semi-colon (;))
However
You probably don't want to mess around with the php.ini setting, as this will affect all php files. If you put another site on your server which tries to include a file with the same name as one in your custom directory you're going to end up in a confusing situation.
I suggest you either qualify your includes:
include('../custom_directory/file.php');
include('/var/custom_directory/file.php');
include(SOURCE_DIR . 'file.php');
Or use set_include_path at the start of your script:
$path = '/var/custom_directory';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);
I got a quick test to test your requirement.
(environment: CentOs 7.1, Apache/2.4.6 and PHP/5.4.16.)
I created a ‘includes’ folder in ‘/var/www/’ folder besides ‘html’, shows like:
Then I set include_path = ".:/var/www/includes" in php.ini.
In the includes folder I put a test class file named phpinfo.class.php with simple code:
class phpInfo{
public function echoinfo(){
phpinfo();
}
}
And in html folder, there is a test PHP file with simple code:
require('phpinfo.class.php');
phpInfo::echoinfo();
It worked fine to me.
So you may double check your files and path.
update
I moved the includes folder under to /var/ beside 'html', and modified the php.ini, and still worked fine to me, and the setting of include_path will be shown in the php runtime environment, we can check the configuration.
I'm experiencing some weirdness trying to setup PEAR on my development machine (Windows XP).
The process is simple enough and everything makes sense, but I'm trying to use one of the installed packages which calls on the PEAR.php file and am getting:
Failed opening required 'PEAR.php' (include_path='.;C:\Program Files\PHP\PEAR')
It's a pretty straightforward error to get assuming the file/path doesn't exist, except I've checked and double checked - it absolutely does - right down to capitalisation (which I know doesn't matter on Windows normally but still...)
What can I possibly have overlooked that means the file can't be opening?
Just to re-iterate, the file/dir DEFINITELY exists as C:\Program Files\PHP\PEAR\PEAR.php - and I have also tried:
forward slashes
short dir names (Progra~1)
all lower case (even though the files are as is) and even setting the include path to
ONLY that directory.
test.php in same directory
test.php in c:\ and with include path set to c:\ and just \
PHP (5.2.6) is NOT running in safe mode, and the web server is Apache 2.
Maybe your php configuration has open_basedir set? If so, set it's value to none.
Try one of these:
C:/Program\ Files/PHP/PEAR/PEAR.php
C:/Program Files/PHP/PEAR/PEAR.php
I am getting the following error from Apache
[Sat Mar 19 23:10:50 2011] [warn] mod_fcgid: stderr: PHP Fatal error: require_once() [function.require]: Failed opening required '/common/configs/config_templates.inc.php' (include_path='.:/usr/share/pear:/usr/share/php') in /home/viapics1/public_html/common/configs/config.inc.php on line 158
I am definately not an expert of Apache but the file config.inc.php & config_templates.inc.php are there. I also tried navigating to a test.html page I placed in common/configs/ so I assume there is no rights issues going on. I also set the rights on config_templates.inc.php to give everyone read, write, and execute rights. Not sure what to do at this point, I checked to see if there was a /usr/share/php directory and I found there was not but when I did yum install php it said it had the latest. Ideas?
It's not actually an Apache related question. Nor even a PHP related one.
To understand this error you have to distinguish a path on the virtual server from a path in the filesystem.
require operator works with files. But a path like this
/common/configs/config_templates.inc.php
only exists on the virtual HTTP server, while there is no such path in the filesystem. The correct filesystem path would be
/home/viapics1/public_html/common/configs/config_templates.inc.php
where
/home/viapics1/public_html
part is called the Document root and it connects the virtual world with the real one. Luckily, web-servers usually have the document root in a configuration variable that they share with PHP. So if you change your code to something like this
require_once $_SERVER['DOCUMENT_ROOT'].'/common/configs/config_templates.inc.php';
it will work from any file placed in any directory!
Update: eventually I wrote an article that explains the difference between relative and absolute paths, in the file system and on the web server, which explains the matter in detail, and contains some practical solutions. Like, such a handy variable doesn't exist when you run your script from a command line. In this case a technique called "a single entry point" is to the rescue. You may refer to the article above for the details as well.
If you have SELinux running, you might have to grant httpd permission to read from /home dir using:
sudo setsebool httpd_read_user_content=1
Run php -f /common/configs/config_templates.inc.php to verify the validity of the PHP syntax in the file.
You could fix it with the PHP constant __DIR__
require_once __DIR__ . '/common/configs/config_templates.inc.php';
It is 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. 1
Just in case this helps anybody else out there, I stumbled on an obscure case for this error triggering last night. Specifically, I was using the require_once method and specifying only a filename and no path, since the file being required was present in the same directory.
I started to get the 'Failed opening required file' error at one point. After tearing my hair out for a while, I finally noticed a PHP Warning message immediately above the fatal error output, indicating 'failed to open stream: Permission denied', but more importantly, informing me of the path to the file it was trying to open. I then twigged to the fact I had created a copy of the file (with ownership not accessible to Apache) elsewhere that happened to also be in the PHP 'include' search path, and ahead of the folder where I wanted it to be picked up. D'oh!
you can set the include path in php.ini
include_path = ".:/home/viapics1/public_html"
I was having the exact same issue, I triple checked the include paths, I also checked that pear was installed and everything looked OK and I was still getting the errors, after a few hours of going crazy looking at this I realized that in my script had this:
include_once "../Mail.php";
instead of:
include_once ("../Mail.php");
Yup, the stupid parenthesis was missing, but there was no generated error on this line of my script which was odd to me