Alternative to http_response_code in lower versions than php5.4

4

You can get HTTP status in versions prior to PHP 5.4 ( http_status_code is only supported in PHP5.4 +)?

I'm creating a custom error page system, it's not going to be a system for a specific project, but as a matter of compatibility I'd like to know if it's possible to detect the state of PHP without using http_response_code .

I need to be independent of the server type because the script can run on Apache, Nginx and Lighttpd.

Is this possible? I tried $GLOBALS and $_SERVER['REDIRECT_STATUS'] , but in case of this, it only works in Apache, in php-fpm only gets status 200 .

    
asked by anonymous 29.05.2015 / 00:27

1 answer

3

In order to work in prior to 5.4, such as php5.3 and php5.3, you can create "reserved" urls using ErrorDocument (apache, see alternatives to other servers below), using for example:

.htacces (apache)

ErrorDocument 403 /index.php/RESERVED.HTTP-STATUS-403.html
ErrorDocument 404 /index.php/RESERVED.HTTP-STATUS-404.html

nginx

error_page 404 /RESERVED.HTTP-STATUS-404.html;
error_page 403 /RESERVED.HTTP-STATUS-403.html;

location ~ ^/RESERVED\.HTTP\-STATUS\-(403|404)\.html$ {
    rewrite ^/RESERVED\.HTTP\-STATUS\-(403|404)\.html$ /index.php$0 last;
}

IIS

<httpErrors errorMode="Custom">
    <remove statusCode="403" />
    <remove statusCode="404" />
    <error statusCode="403" path="/index.php/RESERVED.HTTP-STATUS-403.html" responseMode="ExecuteURL" />
    <error statusCode="404" path="/index.php/RESERVED.HTTP-STATUS-501.html" responseMode="ExecuteURL" />
</httpErrors>

PHP

The file should contain this code:

/*Verifica se a função não esta disponível (versões anteriores ao php5.4)*/
if (false === function_exists('http_response_code')) {
    /*Fallback para versões mais antigas que o PHP5.4*/
    function http_response_code($code = null)
    {
        static $currentStatus;

        if ($code === null) {
            if ($currentStatus !== null) {
                return $currentStatus;
            }

            $currentStatus = 200;

            if (empty($_SERVER['PHP_SELF']) === false &&
                preg_match('#/RESERVED\.HTTP\-STATUS\-(\d{3})\.html$#', $_SERVER['PHP_SELF'], $match) > 0)
            {
                $currentStatus = (int) $match[1];
            }
        } elseif (is_int($code) && headers_sent() === false) {
            header('X-PHP-Response-Code: ' . $code, true, $code);
            $currentStatus = $code;
        }

        return $currentStatus;
    }
}
  

Note that the function will always fire for index.php, but you can change it to error.php or to your liking.

    
31.05.2015 / 01:35