PHP documentation for the header()
function tells us:
There are two special-case header calls… 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.
However, I want to return a 200 status code with a Location header. How can I do this, if at all? I have tried a few variations on the following with no luck:
header('Location: https://example.com/foo', true, 200);
http_response_code(200);
header('HTTP/1.1 200 OK', true, 200);
header('Content-Type: application/json');
echo '{"test":"testing"}';
According to my understanding of the PHP source, the first line should do it because of the explicitly specified status code:
if ((SG(sapi_headers).http_response_code < 300 ||
SG(sapi_headers).http_response_code > 399) &&
SG(sapi_headers).http_response_code != 201) {
/* Return a Found Redirect if one is not already specified */
if (http_response_code) { /* user specified redirect code */
sapi_update_response_code(http_response_code);
} else if (SG(request_info).proto_num > 1000 &&
SG(request_info).request_method &&
strcmp(SG(request_info).request_method, "HEAD") &&
strcmp(SG(request_info).request_method, "GET")) {
sapi_update_response_code(303);
} else {
sapi_update_response_code(302);
}
}