PHP Web Fundamentals
Sending a Specific HTTP Status Code
Problem
You want to explicitly set the HTTP status code. For example, you want to indicate that the user is unauthorized to view the page or the page is not found.
Solution
Use http_response_code() to set the response:http_response_code(401);
Discussion
Your web server returns HTTP status code 200 (OK) for most pages processed by PHP. But there are a wide range of status codes, or response codes, that you may need to use.A few popular codes get recipes of their own. When you’re redirecting to a different page, you need to send a 302 (Found) status code. When a person is not allowed to view a page, you send a 401 (Unauthorized).
But there’s always 304 (Not Modified) for conditional GETs, when you should only return content if it’s changed since the last request. This can be used when someone is polling your site and you want to tell them there’s nothing new to retrieve.
Or, the infamous 404 (Not Found), when a page isn’t there. Normally, this is handled by your web server. But if you want to support dynamic URLs, where there aren’t any physical files stored on disk, but you process the URL and respond to it based on information in a database, then you need to handle this yourself when someone tries to fetch an invalid URL.
One great example is WordPress, which responds to URLs based on categories or dates (e.g., /category/php/ or /2014/11/03/). In these cases, whenever someone adds a category or a post on a new date, WordPress can be configured to automatically respond to requests at URLs that match that pattern, even though there aren’t actually files at that location.
With http_response_code(), you provide the status code number and PHP takes care of setting the proper Status Line. For some status codes, including 204 (No Content), the HTTP specification states you must not provide a message body. In these cases, it’s best to send exit() to immediately end the script. This prevents content from being accidentally added later on:
http_response_code(204);
exit();
If you’re stuck on PHP 5.3, use header(), and pass in the status code as the third parameter:
header('HTTP/1.0 204 No Content', true, 204);
No comments:
Post a Comment