Use a global PHP include for your site
Recently I switched from mod_php to FastCGI for serving PHP websites. With all the advantages of being able to run all websites separatly, the drawback is that configuration options like php_value and php_flag in .htaccess or other Apache configurations do not work anymore. There are some hacks that can be loaded as a PHP Module so PHP itself will read .htaccess files, but none of them work quite well. So the other solution is to use ini_set() in a global PHP include file in the very beginning of the PHP application.
Zend Framework applications are quite easy as all request are forwarded to index.php handling all request, so all global settings like include_paths can be handled there. However, with some PHP websites it is quite hard to introduce a common global PHP include file for application that has no single PHP file the application starts with, and it depends on a include_path set with php_value. The solution is to use Apache mod_rewrite to redirect all php request to a single file, proxy.php, that sets the global settings, and runs the original PHP file requested.
Add the following mod_rewrite code to your Apache vhost file or in .htaccess in the document root:
RewriteCond %{REQUEST_FILENAME} ^(.*)\.php$
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.+)$ proxy.php?proxy_script=$1 [QSA]
This will cause all request ending with .php to be redirected to /proxy.php?proxy_script=original_file.php
In the proxy.php file we define following code to set the global settings and handle the original request:
/* Declare global PHP stuff */ set_include_path(get_include_path() . PATH_SEPARATOR . '/home/www/mysite/current/include' . PATH_SEPARATOR . '/home/www/mysite/current/localsettings' ); //register globals ( EVILNESS!! 'm' ) foreach($_REQUEST as $varname => $varvalue) $$varname = $varvalue; /****************************/ $proxy_script = str_replace('..', '.', $_REQUEST['proxy_script']); $script = $_SERVER['DOCUMENT_ROOT'] . '/' . $proxy_script; if (is_readable($script) && $proxy_script != 'proxy.php') { // set environment for the original request $_SERVER['SCRIPT_FILENAME'] = $script; $_SERVER['PHP_SELF'] = $_SERVER['SCRIPT_NAME'] = '/' . $proxy_script; // run original request include($script); } else { header("HTTP/1.1 404 Not Found"); print "<h2>404 not found</h2>"; }
Now every request will be handled properly, while global environment can be set easily in the proxy.php file.
Tags: apache, configuration, fastcgi, mod_php, mod_rewrite, php, php_flag, php_value