Home >Backend Development >PHP Tutorial >Reinforce PHP environment_PHP tutorial
When PHP is run as a module of Apache, the security of Apache itself plays a leading role. Therefore, if configured correctly, PHP should be a very safe environment. However, if PHP is run in CGI mode, it will not be so safe.
The operations mentioned in this article are applicable to both Unix and Windows.
1. Run as an Apache module
Because generally speaking, Apache will run as "nobody" or "www", so PHP is very safe as a module.
If PHP is in a virtual host environment, there may be a danger that users can browse other users' files. A simple script is as follows:
// Assume the document root is located at /usr/local/websites/mydomain
$location = ../; // Go to the upper level directory
$parent = dir( $location );
// Display the current directory: /usr/local/websites
while( $entry = $parent->read()) {
echo $entry .
;
}
$parent->close();
?>
In this way, as long as $location is modified, the user can browse the files of all other users on the virtual host. In order to reduce such dangers, we need to take a look at php.ini and modify the safe_mode, doc_root and usr_dir parameters to restrict the user to his own virtual host environment:
safe_mode = On
doc_root = /usr/ local/apache/htdocs
user_dir = /home/albertxu/htdocs
2. As CGI
You need to be very careful when running PHP as CGI, it may leak information you don’t want others to know.
The first thing to note is that you must place the executable file somewhere other than the document root directory. For example, /usr/local/bin, so all CGI files must start with:
#!/usr/local/bin/php
The way to prevent users from calling CGI directly is to force CGI redirection in Apache:
Action php-script /cgi-bin/php.cgi
AddHandler php-script .php
This will add the following URL