For set http code use with PHP 5.3 or prior (you can create a file called http_response_code.php
and put this content):
/*Check if function is available (php5.3<)*/
if (false === function_exists('http_response_code')) {
/* Fallback */
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;
}
}
For use call:
<?php
require 'foo/bar/http_response_code.php';
$code = http_response_code();
http_response_code(403);
echo 'Initial HTTP code: ', $code, '<br>', PHP_EOL;
echo 'Current HTTP code: ', http_response_code(), '<br>', PHP_EOL;
This code returns:
Initial HTTP code: 200
Current HTTP code: 403
This function check server error using URL reserved, for work use this configs:
.htacces (Apache)
ErrorDocument 403 /error.php/RESERVED.HTTP-STATUS-403.html
ErrorDocument 404 /error.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$ /error.php$0 last;
}
IIS
<httpErrors errorMode="Custom">
<remove statusCode="403" />
<remove statusCode="404" />
<error statusCode="403" path="/error.php/RESERVED.HTTP-STATUS-403.html" responseMode="ExecuteURL" />
<error statusCode="404" path="/error.php/RESERVED.HTTP-STATUS-501.html" responseMode="ExecuteURL" />
</httpErrors>
The error.php
is a example, can change if needed. In your script page use (error.php):
<?php
require 'foo/bar/http_response_code.php';
echo 'Error page, status: ', http_response_code();
For load a "template":
<?php
require 'foo/bar/http_response_code.php';
include 'template/error/http_' . $code . '.php';