Wednesday, June 30, 2010

Configure apache to run php scripts as cgi

The default configuration for apache in debian is to run php scripts using phpmod. Thus, adding the #!/usr/bin/php line at the begining of each php scripts is not required. On the contrast, this line will be printed on the user's browser and will cause errors if session functions are used in the script.
Recently, I was working on a php project for univerisity. The university's server configuration required this directive while my local apache installion that I was using for development did not. Adding and removing this line each time I loaded the code in the university's server was not a practical solution.
First of all, php5-cgi needs to be installed:

#apt-get install php5-cgi

Then mod_php should be disabled (#a2dismod php5) and the actions module should be used instead (#a2enmod actions). In addition, add these lines to /etc/apache2/httpd.conf (create it if it does already exists):

AddHandler php-script .php
Action php-script /cgi-bin/php5

That's all. Then restart apache (#apache2ctl restart).
In order to verify that apache was configured correctly create the following test.php file and make it executable (chmod 775 test.php):

#!/usr/bin/php

Upload it on your site. The server API section should be set to: CGI/FastCGI.

No comments: