I need to respond to a HEAD request with status code 204.
<?php
if($_SERVER['REQUEST_METHOD']=='HEAD') {
ob_clean();
setHeaderStatus(204, true);
// other headers
header('X-Other-123: 123');
header('Location: '.sprintf('%s://%s%s', $_SERVER['REQUEST_SCHEME'],
$_SERVER['HTTP_HOST'], $_SERVER['REQUEST_URI']));
header('Date: '.date('r'));
header('Content-Type: text/html', true);
header('Content-Length: 0', true);
flush();
die;
}
$messages = array( // {{{
// ...
204 => '204 No Content',
// ...
);
function setHeaderStatus($status, $replace = true)
{
Global $messages;
if (headers_sent() === true)
return;
if (strpos(PHP_SAPI, 'cgi') === 0) {
header('Status: '.$messages[$status], $replace);
} else {
header($_SERVER["SERVER_PROTOCOL"].' '.$messages[$status], $replace);
}
}
Testing this with cURL:
curl -i --noproxy 127.0.0.1 -X HEAD http://localhost/test.php
results in:
HTTP/1.1 302 Found
Date: Thu, 20 Feb 2014 07:46:27 GMT
Server: Apache/2.4.4 (Win32) OpenSSL/0.9.8y PHP/5.4.19
X-Powered-By: PHP/5.4.19
X-Other-123: 123
Location: http://localhost/test.php
Content-Type: text/html
So it seems Apache overrides the status code set by PHP?
Thanks in advance.
Try setHeaderStatus(204, true);
after header('Location:...
.
Normally header('Location:...'
will automatic change header status to 301 or 302 to redirect. May be it override your setting.
Solved.
As the PHP manual says:
"The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set."
As I set the 204 code, it was always overridden by the Location header to 302.
What finally solves it is:
header('Location: ...', true, 204 )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.