Month: September 2008

PHP and MySQL in Tomcat with Quercus

Posted on Updated on

I was recently shown Quercus which is the PHP 5 engine implemented in pure Java and hence, can run in a servlet engine like Tomcat. Caucho suggest running it in Resin but for work reasons, I needed to get it running in Tomcat.

It was very easy to get PHP working, but the MySQL integration took a bit more figuring out. All the info I could find on the web assumed you knew all about DBs in Tomcat and didn’t seem to spell it out.

So here is what I did to get it running in Tomcat 6.0

Add the required jars to tomcat’s lib directory

  1. mysql-connector-java-5.1.5-bin.jar (from mysql’s download page)
  2. quercus.jar (in the quercus zip from caucho)
  3. resin-util.jar (in the quercus zip from caucho)
  4. script-10.jar (in the quercus zip from caucho)

Add the database to tomcats context.xml file

<Context>
<Resource name="jdbc/mydatabasehandle" auth="Container"
type="javax.sql.DataSource"
username="mysql_username"
password="mysql_password"
driverClassName="com.mysql.jdbc.Driver"
maxActive="8"
url="jdbc:mysql://mysqlservername:3306/mysql_actual_database_name?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=utf-8&amp;mysqlEncoding=utf8"
maxIdle="4"/>
</Context>

Note: the jdbc url is all one line (up to mysqlEncoding=utf8) but is wrapped by the blog layout.
Note: Those really are &amp; (ampersand A-M-P semicolon). They are passed into the JDBC driver, and it must then convert html chars into text.

Add Quercus support to your web.xml

The quercus zip has an example web.xml file. These pieces below are mostly based on that.
<web-app>
<servlet>
<servlet-name>Quercus Servlet</servlet-name>
<servlet-class>com.caucho.quercus.servlet.QuercusServlet</servlet-class>
 
<!-- Tells Quercus to use the following JDBC database
and to ignore the arguments of mysqli_connect(). -->
<init-param>
<param-name>database</param-name>
<param-value>jdbc/mydatabasehandle</param-value>
</init-param>
 
<servlet-mapping>
<!-- tell tomcat about .php files -->
<servlet-name>Quercus Servlet</servlet-name>
<url-pattern>*.php</url-pattern>
</servlet-mapping>
 
<!-- tell tomcat about my php file called "myscript" (no extension)
so that URLs like /myscript/somepath will get "/somepath"
in php's $_SERVER["PATH_INFO"] variable. -->
 
<servlet-mapping>
<servlet-name>Quercus Servlet</servlet-name>
<url-pattern>/myscript/*</url-pattern>
</servlet-mapping>
 
</servlet>
</web-app>

Use mysql in your PHP code

$dbh = mysqli_connect();
if ($result = mysqli_query($dbh, $sql)){
while ($row = mysqli_fetch_object($result)){
print $row->fieldName;
}
}
mysqli_close($dbh);

Other useful bits and pieces

  • Note the use of the mysqli methods. I was not successful in getting the plain old mysql commands to work.
  • $request is the java request object, so you can do stuff like $request->getUserPrincipal() if you are doing authentication in Tomcat like I was.