How to prevent php from accessing files outside htdocs?

I’m investigating my hacked website under xampp environment. I put my website files in c:\xampp\htdocs\domainhostseotool\, and visit the site as localhost/domainhostseotool. I’m little worried about a possible security risk. Suppose the compromised website has an infected php file which contains the following code:

It would be terrible if php can access files outside the htdocs directory. In fact, this is the situation under the default configuration of xampp.

How to disable php from accessing the files outside specific folders? You can use the open_basedir option in php.ini. Open php.ini, search for the open_basedir line, un-comment the line and set the value of open_basedir to the folders you allow php to access such as:

restart httpd, now if you run the php script that contains file_get_contents as above, you will get the error:

Warning: file_get_contents(): open_basedir restriction in effect. File(c:\xampp\password.txt) is not within the allowed path(s): (c:\xampp\htdocs)

And file_get_contents cannot read the file any more.

You can specify multiple directories(separated by :) for open_basedir, and php scripts are restricted to access files from only those folders.

You can use the php_flag instruction in .htaccess like:

You can also use the php_admin_value instruction in httpd.conf like:

All three methods can prohibit php scripts from accessing files outside allowed directories. Note that the allowed folders include specific directories and their sub-directories.


Posted in tips of hosting