In order for it to work 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 must 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 switch to error.php or to your liking.
Have you considered using the function
curl_getinfo
using as an argumentCURLINFO_HTTP_CODE
? it is available from PHP 4.0.4. In your first sentence there’s a asserting which contradicts the title. =)– stderr
@qmechanik I had already seen this, but the problem is that it only gets the status if it sets first, ie only works if you do this:
<?php http_response_code(404); echo http_response_code();
. This doesn’t work<?php echo http_response_code();
– Guilherme Nascimento
@qmechanik I think I have an idea, I will create a false "Location" and set a variable ENV environment with http status code.
– Guilherme Nascimento
William, have you had any success? about the idea of Curl, could you use the
CURLOPT_NOBODY
to order only the header http and not the whole content, so will decrease the time to get the answer.– stderr
@qmechanik Thanks for the support and interest, I believe I have achieved as close as possible to a usable result. Have any critical suggestions, you are always welcome :)
– Guilherme Nascimento
It would not be enough
header('HTTP/1.1 200 OK');
to simplify?– Bacco
@Bacchus
http_response_code
take or define the code, in case I wanted an alternative that would do both– Guilherme Nascimento