suPHP and .phps PHP code highlighting support

Today a user on one of my web servers asked me why .phps files would only download and not show the highlighted PHP code as expected.

This is usually done by adding the following to your “httpd.conf”…

AddType ‘application/x-httpd-php-source’ .phps

We use the cPanel web hosting control panel and to improve security cPanel recommend using suPHP, which allows PHP scripts to run as a user rather than “nobody”.

This means that adding the above line to “httpd.conf” does not work with suPHP.

So what can be done?

The official word is located in the suPHP FAQ, which says:

Does suPHP support code highlighting by using the “.phps” extension?

suPHP itself has no support for code highlighting. The main reason is that PHP-CGI does not support any input parameter to activate code highlighting. However there is a solution based on a small PHP script and some rewrite rules. You can find the discussion at http://forums.macosxhints.com/archive/index.php/t-23595.html.

So I decided to checkout the suggested link.

I noticed that even though the FAQ suggested using rewrite rules, the forum did not provide any kind of working solution.

Using the PHP code supplied, and a bit of rewrite ingenuity we can get this working as expected.

First, create a file called “phpsource.php”, in this file paste the following code:

<?php
if (substr($_GET[‘file’],strpos($_GET[‘file’],’.’)) == ‘.phps’) {
highlight_file($_GET[‘file’]);
}
?>

Then, in your “.htaccess”, paste the following code:

RewriteRule ^(.+\.phps)$ phpsource.php?file=$1 [L]

Note: If you don’t already have rewrites turned on in your “.htaccess” file, you will also need the line “RewriteEngine On” at the top.

What this will do is pass all “.phps” files through your “phpsource.php” script, and output a highlighted version.

The benefits of this solution is that it’s portable (will work on any server); it won’t(/shouldn’t) break when you upgrade apache or PHP; it’s pretty secure as it’ll only handle .phps files, as expected; it’s quick and effective.