File Access

If only you and people you trust can log into your web server, you don’t need to worry about file permissions for files used by or created by your PHP programs. However, most web sites are hosted on ISP’s machines, and there’s a risk that non-trusted people can read files that your PHP program creates. There are a number of techniques that you can use to deal with file permissions issues.

Restrict Filesystem Access to a Specific Directory

You can set the open_basedir option to restrict access from your PHP scripts to a specific directory. If open_basedir is set php.ini, PHP limits filesystem and I/O functions so that they can operate only within that directory or any of its subdirectories. For example:

open_basedir = /some/path

With this configuration in effect, the following function calls succeed:

unlink("/some/path/unwanted.exe");
include("/some/path/less/travelled.inc");

But these generate runtime errors:

$fp = fopen ("/some/other/file.exe", "r");
$dp = opendir("/some/path/../other/file.exe");

Of course, one web server can run many applications, and each application typically stores files in its own directory. You can configure open_basedir on a per-virtual host basis in your httpd.conf file like this:

<VirtualHost 1.2.3.4>
  ServerName domainA.com
  DocumentRoot /web/sites/domainA
  php_admin_value open_basedir /web/sites/domainA
</VirtualHost>

Similarly, you can configure it per directory or per URL in httpd.conf:

# by directory <Directory /home/httpd/html/app1> php_admin_value ...

Get Programming PHP, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.