Conclusion
In this tutorial, we’ve covered the basics of PHP’s
header()
function and how to use it for sending HTTP status codes. We also discussed some common use cases for sending HTTP status codes, such as redirecting users, handling 404 errors, and preventing browser caching. Now that you have a better understanding of the
header()
function, you can use it effectively in your PHP applications. If you’re looking to hire PHP developers who are skilled in using the
header()
function, reach out to Reintech today.
- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer’s Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to Send HTTP Response Code in PHP
PHP: PHP (Hypertext Preprocessor) is a popular server-side scripting language primarily used for web development. It was created by Rasmus Lerdorf in the mid-1990s and has since become one of the most widely used programming languages for building dynamic websites and web applications.
PHP is embedded within HTML code and executed on the server, generating dynamic web content that is then sent to the user’s web browser. It can interact with databases, handle form data, generate dynamic page content, perform calculations, manipulate files, and much more.
In PHP, there are multiple ways to send an HTTP response code. Here are four commonly used methods:
-
Using http_response_code() function
-
Using the header() function
-
Using the http_response_code header with header() function
-
Using the Response class in a PHP framework
Returning A Status Code In PHP
To return a status code in PHP, the simplest way is to use the http_response_code() function, along with the relevant HTTP status code parameter into your website, followed by the exit() command which stops any more output being set.
This means the likes of 400 bad requests and 404 not found can all be implemented with just one line of code.
Important: The http_response_code and header() commands must be used before any HTML is returned.
Example: Return a 400 bad request status code
http_response_code(400); exit;
Example: Return a 404 not found status code
http_response_code(404); exit;
Example: Return a 301 moved permanently status code
This example php code also requires that you provide the new URL, to which the users browser will automatically redirect. For this you need to use the more details header() function.
http_response_code(301); header('Location: /newlocation.html'); exit;
The exit command means that no other php code or html code will be output from the page.
Here’s example code for a 503 temporary error page that also includes additional information that is shown in the browser.
php-generated 503
This is a 503 error page. The error is returned in the HTTP header and this is just simple HTML that is displayed in the browser.
PHP – An Overview
PHP stands for hypertext preprocessor. As you may have noticed, the acronym is a little confusing and that’s because PHP originally stood for personal home page. Remember, the way we develop websites has changed immensely in the short time the internet has existed, so sometimes terms need to be updated to keep up to modern standards.
Whenever you request a URL, a complex chain occurs between the server and the browser. PHP is usually involved in this process, as it’s responsible for interpreting the data. A common example of where you would see PHP in action is a login page. As you enter your credentials, a request to the server is made, and PHP will communicate with the database to log you in.
Essentially, PHP is a scripting language that is embedded into HTML. For a quick example, left click on any webpage and select ‘view page source’. Doing so will bring up the code that makes up that page. It is your browser that interprets the code into the functional version of the website.
With PHP, code can either be processed client side (HTML, Javascript and CSS) or server side (PHP). In essence, the server side of PHP is software that is installed on the server. This software can include Linux, Apache, MySQL and finally PHP. In that order, these 4 elements make up what’s known as a LAMP stack. The PHP is the scripting layer of this combination which websites and web applications run off.
Common Use Cases for HTTP Status Codes
In this section, we will show you some common use cases for sending HTTP status codes using the
header()
function.
Redirecting Users
To redirect users to another page, you can send a 302 Found status code along with a Location header:
header("HTTP/1.1 302 Found"); header("Location: http://example.com/new_page.php"); exit;
Alternatively, you can use the
$http_response_code
parameter to set the response code:
header("Location: http://example.com/new_page.php", true, 302); exit;
Handling 404 Not Found Errors
If a requested resource is not found, you can send a 404 Not Found status code and display a custom error page:
header("HTTP/1.1 404 Not Found"); include("404_error_page.php"); exit;
Preventing Browser Caching
To prevent browsers from caching your page, you can send appropriate headers with your response:
header("Cache-Control: no-cache, no-store, must-revalidate"); header("Pragma: no-cache"); header("Expires: 0");
Status codes as an array:
$http_status_codes = array(100 => "Continue", 101 => "Switching Protocols", 102 => "Processing", 200 => "OK", 201 => "Created", 202 => "Accepted", 203 => "Non-Authoritative Information", 204 => "No Content", 205 => "Reset Content", 206 => "Partial Content", 207 => "Multi-Status", 300 => "Multiple Choices", 301 => "Moved Permanently", 302 => "Found", 303 => "See Other", 304 => "Not Modified", 305 => "Use Proxy", 306 => "(Unused)", 307 => "Temporary Redirect", 308 => "Permanent Redirect", 400 => "Bad Request", 401 => "Unauthorized", 402 => "Payment Required", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 406 => "Not Acceptable", 407 => "Proxy Authentication Required", 408 => "Request Timeout", 409 => "Conflict", 410 => "Gone", 411 => "Length Required", 412 => "Precondition Failed", 413 => "Request Entity Too Large", 414 => "Request-URI Too Long", 415 => "Unsupported Media Type", 416 => "Requested Range Not Satisfiable", 417 => "Expectation Failed", 418 => "I'm a teapot", 419 => "Authentication Timeout", 420 => "Enhance Your Calm", 422 => "Unprocessable Entity", 423 => "Locked", 424 => "Failed Dependency", 424 => "Method Failure", 425 => "Unordered Collection", 426 => "Upgrade Required", 428 => "Precondition Required", 429 => "Too Many Requests", 431 => "Request Header Fields Too Large", 444 => "No Response", 449 => "Retry With", 450 => "Blocked by Windows Parental Controls", 451 => "Unavailable For Legal Reasons", 494 => "Request Header Too Large", 495 => "Cert Error", 496 => "No Cert", 497 => "HTTP to HTTPS", 499 => "Client Closed Request", 500 => "Internal Server Error", 501 => "Not Implemented", 502 => "Bad Gateway", 503 => "Service Unavailable", 504 => "Gateway Timeout", 505 => "HTTP Version Not Supported", 506 => "Variant Also Negotiates", 507 => "Insufficient Storage", 508 => "Loop Detected", 509 => "Bandwidth Limit Exceeded", 510 => "Not Extended", 511 => "Network Authentication Required", 598 => "Network read timeout error", 599 => "Network connect timeout error");?>Source: Wikipedia "List_of_HTTP_status_codes"
I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.
How can I do this in PHP?
I have a PHP script that needs to make responses with HTTP response codes (status-codes), like HTTP 200 OK, or some 4XX or 5XX code.
How can I do this in PHP?
I just found this question and thought it needs a more comprehensive answer:
As of PHP 5.4 there are three methods to accomplish this:
The
header()
function has a special use-case that detects a HTTP response line and lets you replace that with a custom one
header("HTTP/1.1 200 OK");
However, this requires special treatment for (Fast)CGI PHP:
$sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') header("Status: 404 Not Found"); else header("HTTP/1.1 404 Not Found");
Note: According to the HTTP RFC, the reason phrase can be any custom string (that conforms to the standard), but for the sake of client compatibility I do not recommend putting a random string there.
Note:
php_sapi_name()
requires PHP 4.0.1
There are obviously a few problems when using that first variant. The biggest of which I think is that it is partly parsed by PHP or the web server and poorly documented.
Since 4.3, the
header
function has a 3rd argument that lets you set the response code somewhat comfortably, but using it requires the first argument to be a non-empty string. Here are two options:
header(':', true, 404); header('X-PHP-Response-Code: 404', true, 404);
I recommend the 2nd one. The first does work on all browsers I have tested, but some minor browsers or web crawlers may have a problem with a header line that only contains a colon. The header field name in the 2nd. variant is of course not standardized in any way and could be modified, I just chose a hopefully descriptive name.
The
http_response_code()
function was introduced in PHP 5.4, and it made things a lot easier.
http_response_code(404);
That’s all.
Here is a function that I have cooked up when I needed compatibility below 5.4 but wanted the functionality of the “new”
http_response_code
function. I believe PHP 4.3 is more than enough backwards compatibility, but you never know…
// For 4.3.0 <= PHP <= 5.4.0 if (!function_exists('http_response_code')) { function http_response_code($newcode = NULL) { static $code = 200; if($newcode !== NULL) { header('X-PHP-Response-Code: '.$newcode, true, $newcode); if(!headers_sent()) $code = $newcode; } return $code; } }
headers_sent()is true if you can't add any more headers because content was already sent, not if you have added a header. (2) Sorry, no. Other languages have better support though
http_response_code(and maybe more generally modifying the header) doesn't work anymore after you
echosomething. Hope it helps.
http_response_code()cannot be used to invent custom error codes. For example
http_response_code(930)will cause the apache log file to show 930 correctly, but an error 500 will actually be sent back to the client. Use the
header()method instead for this admittedly weird use case.
http_response_code()is unreliable for reading the status code. Heders set using
header()take precedence, and
HTTP/1.1
Status:
format - at least on FCGI & nginx.
Unfortunately I found solutions presented by @dualed have various flaws.
Using
substr($sapi_type, 0, 3) == 'cgi'
is not enogh to detect fast CGI. When using PHP-FPM FastCGI Process Manager,
php_sapi_name()
returns fpm not cgi
Fasctcgi and php-fpm expose another bug mentioned by @Josh - using
header('X-PHP-Response-Code: 404', true, 404);
does work properly under PHP-FPM (FastCGI)
header("HTTP/1.1 404 Not Found");
may fail when the protocol is not HTTP/1.1 (i.e. 'HTTP/1.0'). Current protocol must be detected using
$_SERVER['SERVER_PROTOCOL']
(available since PHP 4.1.0)
There are at least 2 cases when calling
http_response_code()
result in unexpected behaviour:
For your reference here there is the full list of HTTP response status codes (this list includes codes from IETF internet standards as well as other IETF RFCs. Many of them are NOT currently supported by PHP http_response_code function()): http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
You can easily test this bug by calling:
http_response_code(521);
The server will send "500 Internal Server Error" HTTP response code resulting in errors if you have a custom client application expecting additional HTTP codes.
My solution (for all PHP versions since 4.1.0):
$httpStatusCode = 521; $httpStatusMsg = 'Web server is down'; $phpSapiName = substr(php_sapi_name(), 0, 3); if ($phpSapiName == 'cgi' || $phpSapiName == 'fpm') { header('Status: '.$httpStatusCode.' '.$httpStatusMsg); } else { $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0'; header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg); }
Conclusion
http_response_code() implementation does not support all HTTP response codes and may overwrite the specified HTTP response code with another one from the same group.
The new http_response_code() function does not solve all the problems involved but make things worst introducing new bugs.
The "compatibility" solution offered by @dualed does not work as expected, at least under PHP-FPM.
The other solutions offered by @dualed also have various bugs. Fast CGI detection does not handle PHP-FPM. Current protocol must be detected.
Any tests and comments are appreciated.
Since PHP 5.4 you can use
http_response_code()
for get and set header status code.
Here is an example:
Here is the document of this function in php.net:
Add this line before any output of the body, in the event you aren't using output buffering.
header("HTTP/1.1 200 OK");
Replace the message portion ('OK') with the appropriate message, and the status code with your code as appropriate (404, 501, etc)
If you are here because of WordPress giving 404's when loading the environment, this should fix the problem:
define('WP_USE_THEMES', false); require('../wp-blog-header.php'); status_header( 200 ); //$wp_query->is_404=false; // if necessary
The problem is due to it sending a Status: 404 Not Found header. You have to override that. This will also work:
define('WP_USE_THEMES', false); require('../wp-blog-header.php'); header("HTTP/1.1 200 OK"); header("Status: 200 All rosy");
With the header function. There is an example in the section on the first parameter it takes.
header("HTTP/1.1 200 OK"); http_response_code(201); header("Status: 200 All rosy");
http_response_code(200); not work because test alert 404 https://developers.google.com/speed/pagespeed/insights/
PHP http_response_code() Function
Example
Set the HTTP response status code to 404:
http_response_code(404);?>
http_response_code(404);
?>
Using the header() function
Using the header() function is another method to send an HTTP response code in PHP.
Here’s how you can use it:
In this example, the header() function is used to set the HTTP response code to 200 (OK). The HTTP/1.1 specifies the version of the HTTP protocol, and 200 OK is the response status line.
You can replace “200 OK” with any valid HTTP response status line, such as “404 Not Found”, “500 Internal Server Error”, or “301 Moved Permanently”, depending on the desired response code.
Here’s an example of sending a 404 (Not Found) response code:
The header() function allows you to set various HTTP headers, including the response code. It should be called before any output is sent to the client, as headers must be sent before the response body.
It’s important to note that when using the header() function to set the response code, you need to specify the full response status line, including the HTTP version. The function is available in all versions of PHP.
Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is crucial for proper communication between the server and the client.
Technical Details
Return Value: | If code is set, the previous status code is returned. If code is not set, the current status code is returned |
PHP Version: | 5.4+ |
❮ PHP Network Reference
Status codes, the status of a p[age being requested from a web server can be generated in a number of different ways. Here we show you how this is done in PHP code – a language that can be used to generate HTML web pages directly.
- Why use PHP to generate status codes?
- What are Status Codes?
- HTTP Status Code Types – Overview
- PHP – An Overview
- Returning A Status Code In PHP
- Example: Return a 400 bad request status code
- Example: Return a 404 not found status code
- Example: Return a 301 moved permanently status code
- Why Status Codes Matters For SEO
- Further Reading
When browsing the internet as a user, you are probably unaware of the secret messaging that is being sent back and forth between where the website is being hosted and your browser.
For example, domain names are actually a series of numerical combinations. Status codes are similar in that they give information about if a page has loaded successfully or not, and the root cause of any errors. PHP is a scripting language that can generate status-code data.
While your content management system, possibly (WordPress) and your web server (possibly Apache) can generate these codes, the scripting language PHP, which is the basis of WordPress, can also generate these codes.
Using http_response_code() function
Using the http_response_code() function is one of the methods to send an HTTP response code in PHP. Here’s how you can use it:
In this example, the http_response_code() function is used to set the HTTP response code to 200 (OK). The function sets the HTTP response code for the current request.
You can pass any valid HTTP response code as the parameter to http_response_code(). For example, 404 for Not Found, 500 for Internal Server Error, 301 for Redirect, etc.
Here’s an example of sending a 404 (Not Found) response code:
The http_response_code() function is available in PHP 5.4 and later versions. It is a convenient and straightforward way to set the response code without explicitly using the header() function.
It’s important to note that once you set the HTTP response code using http_response_code(), it becomes part of the response headers. Therefore, it should be called before any output is sent to the client. If you try to set the response code after output has already been sent, it may result in an error.
Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is essential for proper communication between the server and the client.
What are Status Codes?
HTTP status codes are a way that servers communicate with clients (browsers). For the most part, the page loads successfully and so an ‘ok’ 2xx code will be generated. In such a case, status codes remain invisible to the user. But status codes are there to cover all eventualities, such as a 404 error or even a 502 bad gateway, which will be visually displayed on the page as an error message.
Understanding status codes will allow you to enhance your user experience, especially if your website visitors are receiving error codes that originate from your server as an example.
As the practice is quite technical, status codes are usually implemented manually by someone who understands coding such as a web developer. However, if your website is on WordPress, then plugins do exist to help you make sense and implement status codes.
Of course, as a website user, you may also come across status codes on other websites too. For example, 403 forbidden can be generated if you try to access a section of a website that you don’t have permission to view.
Conclusion
Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is essential for proper communication between the server and the client.
Kickstart Your Career
Get certified by completing the course
Get Started
Star
You must be signed in to star a gist
PHP Class for HTTP Response Status Codes
/** |
* StatusCodes provides named constants for |
* HTTP protocol status codes. Written for the |
* Recess Framework (http://www.recessframework.com/) |
* @author Kris Jordan |
* @license MIT |
* @package recess.http |
* usage: |
*/ |
class StatusCodes |
// [Informational 1xx] |
const HTTP_CONTINUE = 100; |
const HTTP_SWITCHING_PROTOCOLS = 101; |
// [Successful 2xx] |
const HTTP_OK = 200; |
const HTTP_CREATED = 201; |
const HTTP_ACCEPTED = 202; |
const HTTP_NONAUTHORITATIVE_INFORMATION = 203; |
const HTTP_NO_CONTENT = 204; |
const HTTP_RESET_CONTENT = 205; |
const HTTP_PARTIAL_CONTENT = 206; |
// [Redirection 3xx] |
const HTTP_MULTIPLE_CHOICES = 300; |
const HTTP_MOVED_PERMANENTLY = 301; |
const HTTP_FOUND = 302; |
const HTTP_SEE_OTHER = 303; |
const HTTP_NOT_MODIFIED = 304; |
const HTTP_USE_PROXY = 305; |
const HTTP_UNUSED = 306; |
const HTTP_TEMPORARY_REDIRECT = 307; |
// [Client Error 4xx] |
const errorCodesBeginAt = 400; |
const HTTP_BAD_REQUEST = 400; |
const HTTP_UNAUTHORIZED = 401; |
const HTTP_PAYMENT_REQUIRED = 402; |
const HTTP_FORBIDDEN = 403; |
const HTTP_NOT_FOUND = 404; |
const HTTP_METHOD_NOT_ALLOWED = 405; |
const HTTP_NOT_ACCEPTABLE = 406; |
const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407; |
const HTTP_REQUEST_TIMEOUT = 408; |
const HTTP_CONFLICT = 409; |
const HTTP_GONE = 410; |
const HTTP_LENGTH_REQUIRED = 411; |
const HTTP_PRECONDITION_FAILED = 412; |
const HTTP_REQUEST_ENTITY_TOO_LARGE = 413; |
const HTTP_REQUEST_URI_TOO_LONG = 414; |
const HTTP_UNSUPPORTED_MEDIA_TYPE = 415; |
const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416; |
const HTTP_EXPECTATION_FAILED = 417; |
// [Server Error 5xx] |
const HTTP_INTERNAL_SERVER_ERROR = 500; |
const HTTP_NOT_IMPLEMENTED = 501; |
const HTTP_BAD_GATEWAY = 502; |
const HTTP_SERVICE_UNAVAILABLE = 503; |
const HTTP_GATEWAY_TIMEOUT = 504; |
const HTTP_VERSION_NOT_SUPPORTED = 505; |
private static $messages = array( |
// [Informational 1xx] |
100 => ‘100 Continue’, 101 => ‘101 Switching Protocols’, |
// [Successful 2xx] |
200 => ‘200 OK’, 201 => ‘201 Created’, 202 => ‘202 Accepted’, 203 => ‘203 Non-Authoritative Information’, 204 => ‘204 No Content’, 205 => ‘205 Reset Content’, 206 => ‘206 Partial Content’, |
// [Redirection 3xx] |
300 => ‘300 Multiple Choices’, 301 => ‘301 Moved Permanently’, 302 => ‘302 Found’, 303 => ‘303 See Other’, 304 => ‘304 Not Modified’, 305 => ‘305 Use Proxy’, 306 => ‘306 (Unused)’, 307 => ‘307 Temporary Redirect’, |
// [Client Error 4xx] |
400 => ‘400 Bad Request’, 401 => ‘401 Unauthorized’, 402 => ‘402 Payment Required’, 403 => ‘403 Forbidden’, 404 => ‘404 Not Found’, 405 => ‘405 Method Not Allowed’, 406 => ‘406 Not Acceptable’, 407 => ‘407 Proxy Authentication Required’, 408 => ‘408 Request Timeout’, 409 => ‘409 Conflict’, 410 => ‘410 Gone’, 411 => ‘411 Length Required’, 412 => ‘412 Precondition Failed’, 413 => ‘413 Request Entity Too Large’, 414 => ‘414 Request-URI Too Long’, 415 => ‘415 Unsupported Media Type’, 416 => ‘416 Requested Range Not Satisfiable’, 417 => ‘417 Expectation Failed’, |
// [Server Error 5xx] |
500 => ‘500 Internal Server Error’, 501 => ‘501 Not Implemented’, 502 => ‘502 Bad Gateway’, 503 => ‘503 Service Unavailable’, 504 => ‘504 Gateway Timeout’, 505 => ‘505 HTTP Version Not Supported’); |
public static function httpHeaderFor($code) |
return ‘HTTP/1.1 ‘.self::$messages[$code]; |
public static function getMessageForCode($code) |
return self::$messages[$code]; |
public static function isError($code) |
return is_numeric($code) && $code >= self::HTTP_BAD_REQUEST; |
public static function canHaveBody($code) |
return |
// True if not in 100s |
($code < self::HTTP_CONTINUE || $code >= self::HTTP_OK) && // and not 204 NO CONTENT |
$code != self::HTTP_NO_CONTENT && // and not 304 NOT MODIFIED |
$code != self::HTTP_NOT_MODIFIED; |
?> |
kingRayhan
commented
Sep 14, 2020
Thank you so much dude
goldingdamien
commented
May 28, 2023
Thanks, good class and list, but missing some codes, so I have provided further information below for reference:
https://github.com/lukasoppermann/http-statushttps://github.com/lukasoppermann/http-status/blob/master/src/Httpstatuscodes.phphttps://stackoverflow.com/questions/3913960/predefined-array-of-http-errors-for-php-usehttps://github.com/for-GET/know-your-http-well/blob/master/json/status-codes.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
How to send HTTP response code in PHP?
There are three approaches to accomplish the above requirement, depending on the version.
For PHP versions 4.0:
In order to send the HTTP response code, we need to assemble the response code. To achieve this, use header() function. The header() function contains a special use-case which can detect a HTTP response line and replace that with a custom one.
header(“HTTP/1.1 200 OK”);
Example:
|
For PHP versions 4.3:
There are obviously a few problems when using first method. The biggest one is that it is partly parsed by PHP and is poorly documented. Since the version 4.3, the header() function has an additional 3rd argument through which we can set the response code. but to use the first argument should be a non-empty string.
header(‘:’, true, 400);
header(‘X_PHP_Response_Code: 400′, true, 400);
The second one is recommended. The header field name in this variant is not standardized and can be modified.
For PHP versions 5.4:
This versions uses http_response_code() function to makes things easier.
http_response_code(400);
Example:
This example uses http_response_code() function to send HTTP response code.
|
Output:
200
HTTP request successfully
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
Last Updated :
26 Mar, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment…
Further Reading
The above gives a brief overview of returning status codes in PHP. However, given the complex nature of coding it’s impossible to cover everything in just one article alone. So we definitely suggest doing some further reading to increase your understanding.
Resources you may find helpful include the official PHP website. In particular, their Using PHP section covers common errors you may encounter, especially as you get to grips with it.
Remember, when building any code it’s essential to test it. Even a small error or even a bug can disrupt the final result, so it’s good to remember that PHP isn’t just about the writing of the script, but seeing it through to a working page. Plus, looking out for any errors that may occur further down the line.
/** |
* Content from http://en.wikipedia.org/wiki/List_of_HTTP_status_codes |
* You may also want a list of unofficial codes: |
* 103 => ‘Checkpoint’, |
* 218 => ‘This is fine’, // Apache Web Server |
* 419 => ‘Page Expired’, // Laravel Framework |
* 420 => ‘Method Failure’, // Spring Framework |
* 420 => ‘Enhance Your Calm’, // Twitter |
* 430 => ‘Request Header Fields Too Large’, // Shopify |
* 450 => ‘Blocked by Windows Parental Controls’, // Microsoft |
* 498 => ‘Invalid Token’, // Esri |
* 499 => ‘Token Required’, // Esri |
* 509 => ‘Bandwidth Limit Exceeded’, // Apache Web Server/cPanel |
* 526 => ‘Invalid SSL Certificate’, // Cloudflare and Cloud Foundry’s gorouter |
* 529 => ‘Site is overloaded’, // Qualys in the SSLLabs |
* 530 => ‘Site is frozen’, // Pantheon web platform |
* 598 => ‘Network read timeout error’, // Informal convention |
* 440 => ‘Login Time-out’, // IIS |
* 449 => ‘Retry With’, // IIS |
* 451 => ‘Redirect’, // IIS |
* 444 => ‘No Response’, // nginx |
* 494 => ‘Request header too large’, // nginx |
* 495 => ‘SSL Certificate Error’, // nginx |
* 496 => ‘SSL Certificate Required’, // nginx |
* 497 => ‘HTTP Request Sent to HTTPS Port’, // nginx |
* 499 => ‘Client Closed Request’, // nginx |
* 520 => ‘Web Server Returned an Unknown Error’, // Cloudflare |
* 521 => ‘Web Server Is Down’, // Cloudflare |
* 522 => ‘Connection Timed Out’, // Cloudflare |
* 523 => ‘Origin Is Unreachable’, // Cloudflare |
* 524 => ‘A Timeout Occurred’, // Cloudflare |
* 525 => ‘SSL Handshake Failed’, // Cloudflare |
* 526 => ‘Invalid SSL Certificate’, // Cloudflare |
* 527 => ‘Railgun Error’, // Cloudflare |
*/ |
return [ |
100 => ‘Continue’, |
101 => ‘Switching Protocols’, |
102 => ‘Processing’, // WebDAV; RFC 2518 |
103 => ‘Early Hints’, // RFC 8297 |
200 => ‘OK’, |
201 => ‘Created’, |
202 => ‘Accepted’, |
203 => ‘Non-Authoritative Information’, // since HTTP/1.1 |
204 => ‘No Content’, |
205 => ‘Reset Content’, |
206 => ‘Partial Content’, // RFC 7233 |
207 => ‘Multi-Status’, // WebDAV; RFC 4918 |
208 => ‘Already Reported’, // WebDAV; RFC 5842 |
226 => ‘IM Used’, // RFC 3229 |
300 => ‘Multiple Choices’, |
301 => ‘Moved Permanently’, |
302 => ‘Found’, // Previously “Moved temporarily” |
303 => ‘See Other’, // since HTTP/1.1 |
304 => ‘Not Modified’, // RFC 7232 |
305 => ‘Use Proxy’, // since HTTP/1.1 |
306 => ‘Switch Proxy’, |
307 => ‘Temporary Redirect’, // since HTTP/1.1 |
308 => ‘Permanent Redirect’, // RFC 7538 |
400 => ‘Bad Request’, |
401 => ‘Unauthorized’, // RFC 7235 |
402 => ‘Payment Required’, |
403 => ‘Forbidden’, |
404 => ‘Not Found’, |
405 => ‘Method Not Allowed’, |
406 => ‘Not Acceptable’, |
407 => ‘Proxy Authentication Required’, // RFC 7235 |
408 => ‘Request Timeout’, |
409 => ‘Conflict’, |
410 => ‘Gone’, |
411 => ‘Length Required’, |
412 => ‘Precondition Failed’, // RFC 7232 |
413 => ‘Payload Too Large’, // RFC 7231 |
414 => ‘URI Too Long’, // RFC 7231 |
415 => ‘Unsupported Media Type’, // RFC 7231 |
416 => ‘Range Not Satisfiable’, // RFC 7233 |
417 => ‘Expectation Failed’, |
418 => ‘I\’m a teapot’, // RFC 2324, RFC 7168 |
421 => ‘Misdirected Request’, // RFC 7540 |
422 => ‘Unprocessable Entity’, // WebDAV; RFC 4918 |
423 => ‘Locked’, // WebDAV; RFC 4918 |
424 => ‘Failed Dependency’, // WebDAV; RFC 4918 |
425 => ‘Too Early’, // RFC 8470 |
426 => ‘Upgrade Required’, |
428 => ‘Precondition Required’, // RFC 6585 |
429 => ‘Too Many Requests’, // RFC 6585 |
431 => ‘Request Header Fields Too Large’, // RFC 6585 |
451 => ‘Unavailable For Legal Reasons’, // RFC 7725 |
500 => ‘Internal Server Error’, |
501 => ‘Not Implemented’, |
502 => ‘Bad Gateway’, |
503 => ‘Service Unavailable’, |
504 => ‘Gateway Timeout’, |
505 => ‘HTTP Version Not Supported’, |
506 => ‘Variant Also Negotiates’, // RFC 2295 |
507 => ‘Insufficient Storage’, // WebDAV; RFC 4918 |
508 => ‘Loop Detected’, // WebDAV; RFC 5842 |
510 => ‘Not Extended’, // RFC 2774 |
511 => ‘Network Authentication Required’, // RFC 6585 |
]; |
angeldelrio
commented
May 20, 2018
Just was I was looking for. Thanks!
rajeshkumar-arch
commented
Jun 20, 2018
Thanks
ghost
commented
Jul 1, 2018
Thanks!
benfavre
commented
Aug 7, 2018
Thanks !! <3
prajyotpro
commented
Aug 17, 2018
much needed. Thanks
romanzhivo
commented
May 20, 2019
A lot of thanks! 🙂
zanderwar
commented
Jul 18, 2019
420, 424, 451 have duplicate entries, the former would never be revealed may as well remove them
pavrip
commented
Feb 23, 2020
Thank you for this
hondero2552
commented
Apr 2, 2020
THANK YOU!! Just what I was looking for!
ramirespoa
commented
Apr 9, 2020
Thank you!
hiperesp
commented
Apr 11, 2020
Thank you!
cristiancarrino
commented
May 10, 2020
<3
shapyz
commented
Nov 21, 2020
Thank you
gaffling
commented
Apr 3, 2021
•
$http_status_codes = array(100 => ‘Continue’,101 => ‘Switching Protocols’,102 => ‘Processing’,200 => ‘OK’,201 => ‘Created’,202 => ‘Accepted’,203 => ‘Non-Authoritative Information’,204 => ‘No Content’,205 => ‘Reset Content’,206 => ‘Partial Content’,207 => ‘Multi-Status’,300 => ‘Multiple Choices’,301 => ‘Moved Permanently’,302 => ‘Found’,303 => ‘See Other’,304 => ‘Not Modified’,305 => ‘Use Proxy’,306 => ‘(Unused)’,307 => ‘Temporary Redirect’,308 => ‘Permanent Redirect’,400 => ‘Bad Request’,401 => ‘Unauthorized’,402 => ‘Payment Required’,403 => ‘Forbidden’,404 => ‘Not Found’,405 => ‘Method Not Allowed’,406 => ‘Not Acceptable’,407 => ‘Proxy Authentication Required’,408 => ‘Request Timeout’,409 => ‘Conflict’,410 => ‘Gone’,411 => ‘Length Required’,412 => ‘Precondition Failed’,413 => ‘Request Entity Too Large’,414 => ‘Request-URI Too Long’,415 => ‘Unsupported Media Type’,416 => ‘Requested Range Not Satisfiable’,417 => ‘Expectation Failed’,418 => “I’m a teapot”,419 => ‘Authentication Timeout’,420 => ‘Enhance Your Calm’,422 => ‘Unprocessable Entity’,423 => ‘Locked’,424 => ‘Failed Dependency’,424 => ‘Method Failure’,425 => ‘Unordered Collection’,426 => ‘Upgrade Required’,428 => ‘Precondition Required’,429 => ‘Too Many Requests’,431 => ‘Request Header Fields Too Large’,444 => ‘No Response’,449 => ‘Retry With’,450 => ‘Blocked by Windows Parental Controls’,451 => ‘Unavailable For Legal Reasons’,494 => ‘Request Header Too Large’,495 => ‘Cert Error’,496 => ‘No Cert’,497 => ‘HTTP to HTTPS’,499 => ‘Client Closed Request’,500 => ‘Internal Server Error’,501 => ‘Not Implemented’,502 => ‘Bad Gateway’,503 => ‘Service Unavailable’,504 => ‘Gateway Timeout’,505 => ‘HTTP Version Not Supported’,506 => ‘Variant Also Negotiates’,507 => ‘Insufficient Storage’,508 => ‘Loop Detected’,509 => ‘Bandwidth Limit Exceeded’,510 => ‘Not Extended’,511 => ‘Network Authentication Required’,598 => ‘Network read timeout error’,599 => ‘Network connect timeout error’);
GabrieleMartini
commented
Apr 4, 2021
•
418 => ‘I’m a teapot’,
@gaffling Three single quotes in this string
gaffling
commented
Apr 4, 2021
@GabrieleMartini the Backslash was dropped by GitHub, but maybe a developer should be able to fix that 😉
In this tutorial, we will explore PHP’s
header()
function and its use for sending HTTP status codes from the server to the client. We will demonstrate how to send different HTTP status codes using the
header()
function and how to handle common use cases within your PHP applications. By the end of this tutorial, you should have a solid understanding of the
header()
function and how to use it effectively in your projects.
Using the http_response_code header with header() function
Using the http_response_code header with the header() function is another method to send an HTTP response code in PHP. Here’s how you can use it:
In this example, the header() function is used to set the HTTP response code to 200 (OK). The “http/1.1” specifies the version of the HTTP protocol, and “200 OK” is the response status line.
You can replace “200 OK” with any valid HTTP response status line, such as “404 Not Found”, “500 Internal Server Error”, or “301 Moved Permanently”, depending on the desired response code.
Here’s an example of sending a 404 (Not Found) response code:
When using this method, you need to specify the full response status line, including the HTTP version, in the header() function.
It’s important to note that the header() function should be called before any output is sent to the client, as headers must be sent before the response body.
This method is available in all versions of PHP and provides flexibility in setting the response code using the http_response_code header with the header() function.
Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is crucial for proper communication between the server and the client.
Sending HTTP Status Codes with `header()`
To send an HTTP status code using the
header()
function, you need to provide a header string in the format
"HTTP/x.y STATUS_CODE STATUS_MESSAGE"
, where
x.y
is the HTTP protocol version (e.g., 1.1),
STATUS_CODE
is the 3-digit status code (e.g., 200), and
STATUS_MESSAGE
is the corresponding status message (e.g., “OK”).
Here’s an example of sending a 200 OK status code:
header("HTTP/1.1 200 OK");
And here’s an example of sending a 404 Not Found status code:
header("HTTP/1.1 404 Not Found");
Why use PHP to generate status codes?
PHP is the language that WordPress is built on. If you are thinking of adapting your WordPress theme, or even writing additional pages using PHP, you might want to use status codes to return a positive status code, to redirect the request to another page or site, or to advise that a page is not available. For example, you have deleted a lot of content and you want to provide a special landing page to tell robots and users that this specific content has been removed, and why. Or, you may want to write a simple PHP script to tell users when the site is under maintenance.
Why Status Codes Matters For SEO
As the name suggests, SEO is all about catering to search engines, so that users are more likely to come across your site. Search engines actively crawl status codes and will determine how your site is indexed as a result.
For example, if your site has plenty of 404 errors that exist from internal or external, links then this can harm your rankings because this will not generate a helpful experience for users. In a nutshell, search engines are looking out for healthy status codes, as this indicates everything is ticking over as it should be.
What is the `header()` Function?
The
header()
function is a built-in PHP function that allows you to send raw HTTP headers to the client. It is commonly used to set the Content-Type, redirect users, and send HTTP status codes. The syntax for the
header()
function is as follows:
header(string $header, bool $replace = true, int $http_response_code = 0)
Here are the function parameters:
- $header: The header string to send.
-
$replace: (Optional) Indicates whether the header should replace the previously set header with the same name. If set to
false
, the new header will be added alongside any existing headers with the same name. The default value is
true
. - $http_response_code: (Optional) Forces the HTTP response code to the specified value. The default value is , which means the response code is not modified.
Using the Response class in a PHP framework
Using the Response class in a PHP framework is another method to send an HTTP response code. This method is specific to PHP frameworks such as Laravel, Symfony, or CodeIgniter. The exact implementation may vary depending on the framework you are using.
Here’s an example using Laravel
setStatusCode(200); ?>
In this example, the response() function is used to create an instance of the Response class. The empty string ” passed as the content represents an empty response body. Then, the setStatusCode() method is used to set the HTTP response code to 200 (OK).
You can replace 200 with any valid HTTP response code according to your requirements. Additionally, you can provide content as a parameter to the response() function if you want to send a response body along with the code.
The Response class in PHP frameworks provides various methods to customize the response, such as setting headers, adding cookies, and setting the content type.
The exact syntax and methods may differ depending on the PHP framework you are using. Refer to the documentation of your specific framework to learn more about using the Response class to send an HTTP response code.
Remember to set the appropriate response code based on the result of your script or the specific requirements of your application. Providing accurate and meaningful HTTP response codes is essential for proper communication between the server and the client.
Keywords searched by users: php http status code
Categories: Chi tiết 34 Php Http Status Code
See more here: kientrucannam.vn
See more: https://kientrucannam.vn/vn/