Fixing PHP-FPM’s SCRIPT_NAME Bug The Brute Force Way

It’s not really news that PHP in it’s CGI or FPM flavor has slight to modest problems getting it’s environment right when using Apache as the front end web server, especially the $_SERVER[‘SCRIPT_NAME’] variable many scripts rely on to determine their true location on the hard drive. This erratic behavior is heavily documented in bug reports 51983 and 55208. As is common practice for the PHP-FPM team, their approach is to sit still and wait until this bug goes away on it’s own. This approach, proven to work for many politicians, may however not work for those folks, that need a solution to the problem at hand. A quite simple solution that unfortunately requires to recompile PHP is the following brute force patch for PHP 5.3.8:

--- php-5.3.8/sapi/fpm/fpm/fpm_main.c.org   2011-07-18 23:03:44.000000000 +0200
+++ php-5.3.8/sapi/fpm/fpm/fpm_main.c.  2011-11-24 18:29:37.000000000 +0100
@@ -1084,6 +1084,7 @@
 {
    char *env_script_filename = sapi_cgibin_getenv("SCRIPT_FILENAME", sizeof("SCRIPT_FILENAME") - 1 TSRMLS_CC);
    char *env_path_translated = sapi_cgibin_getenv("PATH_TRANSLATED", sizeof("PATH_TRANSLATED") - 1 TSRMLS_CC);
+   char *env_redirect_url = sapi_cgibin_getenv("REDIRECT_URL", sizeof("REDIRECT_URL") - 1 TSRMLS_CC);
    char *script_path_translated = env_script_filename;
    char *ini;
    int apache_was_here = 0;
@@ -1118,6 +1119,16 @@
 
        /* Hack for buggy IIS that sets incorrect PATH_INFO */
        char *env_server_software = sapi_cgibin_getenv("SERVER_SOFTWARE", sizeof("SERVER_SOFTWARE") - 1 TSRMLS_CC);
+                if (env_redirect_url &&
+                        strncmp(env_server_software, "Apache", sizeof("Apache")-1) == 0) {
+                        /*
+                         * If we have an env_redirect_url and the web server is Apache
+                         * it's very likely that env_redirect_url is the one we really
+                         * want
+                         */
+                        env_script_name = _sapi_cgibin_putenv("SCRIPT_NAME", env_redirect_url TSRMLS_CC);
+                }
+
        if (env_server_software &&
            env_script_name &&
            env_path_info &&
@@ -1159,7 +1170,7 @@
        if (CGIG(fix_pathinfo)) {
            struct stat st;
            char *real_path = NULL;
-           char *env_redirect_url = sapi_cgibin_getenv("REDIRECT_URL", sizeof("REDIRECT_URL") - 1 TSRMLS_CC);
+           // char *env_redirect_url = sapi_cgibin_getenv("REDIRECT_URL", sizeof("REDIRECT_URL") - 1 TSRMLS_CC);
            char *env_document_root = sapi_cgibin_getenv("DOCUMENT_ROOT", sizeof("DOCUMENT_ROOT") - 1 TSRMLS_CC);
            char *orig_path_translated = env_path_translated;
            char *orig_path_info = env_path_info;