The Documented Code
In PHP documentation, the suggested code for returning 404 Not Found
is:
header("HTTP/1.0 404 Not Found");
I wanted the shortest possible code for the PHP framework I'm writing. So, I don't want an array of response texts that accompany the codes; that is simply way too long.
Testing the Alternatives
I decided to test a bunch of variations to see if I could make it shorter. These are what I tested and the results:
header("HTTP/1.1 404");
header("HTTP/1 404");
header("HTTP/ 404");
header("HTTP 404");
header("HTTP/1.1",0,404);
header("HTTP/1",0,404);
header("HTTP/",0,404);
header("HTTP",0,404);
header("",0,404);
header("/",0,404);
header("1",0,404);
header(1,0,404);
header(0,0,404);
Found it!
The Shortest Code
So, the shortest code is:
header(0,0,404);
It is a surprise for me because the documentation says that the 1st parameter must not be empty for the 3rd parameter to work, and integer 0 is considered empty by the function empty()
.
I tested this in PHP 5.3.10. Of course, you could use http_response_code()
in PHP 5.4.0 and up, but it's not as short.
I didn't test all possible response codes, but the ones I did test (400-420 and 500-510) work just fine. For unknown codes, you'll either get "unused
" (such as "420 unused
") or "500 Internal Server Error
" if you go too far (such as 499).
A friendly warning
As mentioned by AlBundyLoves69, using an undocumented feature is dangerous as it will likely break your code in the future. I'm not going to use it anyway, because I won't be able to do this:
header("HTTP/1.0 404 This is not the page you're looking for");
Or something more serious, for instance, if one can't find a resource at /api/resource/1234
:
header("HTTP/1.0 404 Resource ID 1234 not found");
As a confirmation that the server received the request correctly.
But exploring is fun for me and I want to share what I found. More feedbacks are welcome.
History
- 6th December, 2015: Original version
- 8th December, 2015: Updated: added a warning section