Friday, July 2, 2010

PHP 5 with Tomcat 6 as FastCGI (Mac OS X)

Let's launch php5 FactCGI with the Tomcat 6 CGI interface.


QuickStart


Let's assume you have fastcgi php installed.

For Max OS X (you need to have MacPorts)


sudo port install fcgi

sudo port install php5 +fastcgi


For simplicity I'm using the following wrapper on my OS X:


#!/bin/sh

#

export REDIRECT_STATUS="200"

/opt/local/bin/php-cgi -d allow_url_include=On -a $*


Now we will create a web application:


webapps/php/WEB-INFI/web.xml


<?xml version="1.0" encoding="ISO-8859-1"?>

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

version="2.5">

<servlet>

<servlet-name>cgi</servlet-name>

<servlet-class>org.apache.catalina.servlets.CGIServlet</servlet-class>


<init-param>

<param-name>debug</param-name>

<param-value>6</param-value>

</init-param>


<init-param>

<param-name>executable</param-name>

<param-value>/usr/bin/php-cgi</param-value>

</init-param>


<init-param>

<param-name>cgiPathPrefix</param-name>

<param-value></param-value>

</init-param>

<load-on-startup>5</load-on-startup>

</servlet>


<!-- The mapping for the CGI Gateway servlet -->

<servlet-mapping>

<servlet-name>cgi</servlet-name>

<url-pattern>*.php</url-pattern>

</servlet-mapping>


<welcome-file-list>

<welcome-file>index.php</welcome-file>

</welcome-file-list>

</web-app>


webapps/php/WEB-INFI/context.xml


<?xml version="1.0" encoding="UTF-8"?>

<Context antiResourceLocking="false" privileged="true" />


webapps/php/index.php


<? phpinfo(); ?>


Now some bits of explanations:


We had configured our php5 cgi in web.xml as described in Apache Tomcat 6.0 - CGI How To. But one bit of information that is missing is the context setup: org.apache.catalina.servlets.CGIServlet is a privileged servlet, so you need to put privileged="true" into your context.xml


Some online tips & tutorials say to uncomment CGI configuration in the global ${catalina.base}/conf/web.xml, but if you do that all your non-privileged applications will fail to start. Also we don't want to enable CGI for all deployed applications really.


The wrapper I'm using is pretty basic - it runs interactively. You will definitely need more advanced one :) Current PHP 5.3.2 FastCGI requires environment variable REDIRECT_STATUS to be set due to security reasons. You can specify "-d cgi.force_redirect=Off" in your wrapper to disable this requirement.


So, the long awaited result:





1 comments:

Spiral said...

I found your post very useful but so far, I am unsuccessful. At the beginning, you mention that you are using the following wrapper on OS X:

#!/bin/sh
#
export REDIRECT_STATUS="200"
/opt/local/bin/php-cgi -d allow_url_include=On -a $*

I do not know what you mean by this and, perhaps, it is why this does not work for me.