Chuyển tới nội dung
Home » Php Get Http Status Code | What Are Http Status Codes?

Php Get Http Status Code | What Are Http Status Codes?

PHP-Send HTTP Get/Post Request and Read JSON response

Need Help?

If you have questions about what response status codes your website returns, or want help resolving any related problems with those response codes, please check out my book, Tech SEO Guide, or contact me.

What are HTTP status codes?

HTTP status codes are three-digit responses from the server to the browser-side request. Everyone has probably gotten the classic 404 page-not-found error. That is an HTTP client error status code and there are a lot more of them.

These status codes (also called response status codes) serve as a means of communication between the server and the internet browser and there are multiple code classes based on the type of information they are communicating. The differences in classes are indicated through the first digit of the error code, for example: just like a 404, any other 4xx will mean that in some way the page or website could not be reached, while a 2xx means that your request was successfully completed.

What does a 1xx Informational status code mean?

A 1xx Informational status code means that the server has received the request and is continuing the process. A 1xx status code is purely temporary and is given while the request processing continues. For most tasks you won’t encounter these much, as it’s not the final response to the request.

What does 100 Continue mean?

The 100 Continue status code means that the initial part of the request has been received by the server and that the client should proceed with the request or ignore the response if the request has already finished.

What does 101 Switching protocols mean?

The 101 Switching protocols status code means that the server understands the Upgrade header field request and indicates which protocol it is switching to.

What does 102 Processing mean?

The 102 Processing status code means that the server has accepted the full request but has not yet completed it and no response is available as of yet.

What does 103 Early Hints mean?

The 103 Early hints status code is intended to be used to allow the user agent to preload resources, while the server prepares a response. It is intended to be primarily used with the Link Header.

PHP-Send HTTP Get/Post Request and Read JSON response
PHP-Send HTTP Get/Post Request and Read JSON response

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.

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.

  • 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

Learn HTTP Status Codes In 10 Minutes
Learn HTTP Status Codes In 10 Minutes

Complete list of HTTP Status Codes

Status code Meaning
1xx Informational
100 Continue
101 Switching protocols
102 Processing
103 Early Hints
2xx Succesful
200 OK
201 Created
202 Accepted
203 Non-Authoritative Information
204 No Content
205 Reset Content
206 Partial Content
207 Multi-Status
208 Already Reported
226 IM Used
3xx Redirection
300 Multiple Choices
301 Moved Permanently
302 Found (Previously “Moved Temporarily”)
303 See Other
304 Not Modified
305 Use Proxy
306 Switch Proxy
307 Temporary Redirect
308 Permanent Redirect
4xx Client Error
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 Payload Too Large
414 URI Too Long
415 Unsupported Media Type
416 Range Not Satisfiable
417 Expectation Failed
418 I’m a Teapot
421 Misdirected Request
422 Unprocessable Entity
423 Locked
424 Failed Dependency
425 Too Early
426 Upgrade Required
428 Precondition Required
429 Too Many Requests
431 Request Header Fields Too Large
451 Unavailable For Legal Reasons
5xx Server Error
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
510 Not Extended
511 Network Authentication Required

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.

HTTP Headers In PHP - Request & Response Headers - Full PHP 8 Tutorial
HTTP Headers In PHP – Request & Response Headers – Full PHP 8 Tutorial

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");

What status code is returned by a website when the browser request is successful?

With all these HTTP status codes – It can be a bit daunting to figure if any of them are good. But some of them are. A browser will return a 2xx status code if the browser request was successful. So a 2xx code is the one you want to see. The 200 status code means that the browser’s request was successful and received, understood, and accepted.

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.

PHP http status code 1049 with MySQL
PHP http status code 1049 with MySQL


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"

This is part of a PHP script I am putting together. Basically a domain ($domain1) is defined in a form and a different message is displayed, based on the response code from the server. However, I am having issues getting it to work. The 3 digit response code is all I am interested in.

Here is what I have so far:


function get_http_response_code($domain1) { $headers = get_headers($domain1); return substr($headers[0], 9, 3); foreach ($get_http_response_code as $gethead) { if ($gethead == 200) { echo "OKAY!"; } else { echo "Nokay!"; } } }

PHP http_response_code() Function

Example

Set the HTTP response status code to 404:


http_response_code(404);?>

http_response_code(404);

?>

Reviewing Specific Response Codes

Status 200Status 201

One of the response codes returned might be a status 201 instead of the expected status 200. A status 201 indicates that a resource has been created and the expected behavior is that the page returning the 201 should provide a location indicating where to locate that newly created resource. More often than not, you’ll see this status code used within APIs instead of websites. However, certain web apps do use 201 response codes in response to user behavior, such as after a user uploads a new file or adds a post to a forum. If your website is returning a status 201, you want to make sure it is used appropriately and that the location of the new resource is correctly stated as part of the response. For example, if you run a status 201 page through WebSniffer, you should see a line for Location in the HTTP Response Header table.

Checking 301s & 302s: Following Redirect Chains

If any URLs return a 301 or 302 response code, that means the URL redirects somewhere else. In these cases, it is helpful to know where those URLs redirect. As well, you’ll want to check if the redirect happens in one step or multiple steps.

Need help on redirects? For more information about redirects, including how to address redirect chains, check out my in-depth guide to redirects.

There are several tools to check redirects and identify redirect chains, including WhereGoes.com and HTTPStatus. Using HTTPStatus as an example, begin by entering a URL (or multiple URLs) that redirects. For example, I’ve entered “https://www.elementive.com/redirect/chain”, which redirects to the website’s home page through multiple redirect hops.

The results will then tell you where this URL redirects to. In this example, /redirect/chain redirects to chain1, which redirects to chain2, which redirects to chain3, which redirects to chain4, and chain-4 redirects to Elementive’s home page.

We can see similar results in WhereGoes.

304: Not Modified Response Code

A 304 HTTP response code is not an error. Instead, a 304 response code means the requested file has not been modified since the previous request was made and has been cached. This can be a way to help speed up a website because 304 responses can help reduce unnecessary network traffic.

Before requesting a file, the browser or robot checks if a cached version of that file already exists. If a browser or robot has a cached version of the file, it first sends a conditional request to the server, including the last modified date for the cached file via the If-Modified-Since HTTP Header.

The server then checks if the file has been modified since the stated date. If the file has been modified, then the file is sent from the server to the browser. This loads it as normal.

If the file has not been modified since that date, the server responds with a 304 Not Modified status code, and no file is sent. When a robot or a browser receives the 304 response code, then the robot knows the cached version of the file can be used.

This saves bandwidth and time for robots and browsers because the condition request and subsequent 304 response are significantly smaller than sending the whole resource again.

For Googlebot, this will improve processing time for files, allowing Google to use saved copies of files. Especially resource files, including images, CSS, or JavaScript files. This also improves crawl efficiency, which is especially important for larger websites.

400: Bad Request

A 400 status is a general error message indicating the server is unable to correctly process the request. The status code does not specify the exact reason for the error, simply indicating the request was “bad”. One common cause is malformed URLs that the server does not understand. So, when this is detected, it is important to check if query strings added to a URL are causing a problem. Sometimes, cookies or an outdated cache can cause processing issues as well.

If detected, Googlebot assumes the page with that status code does not exist. As a result, URLs returning a 400 Bad Request status code will be treated similarly to a URL returning a 404 Not Found status code. As a result, this can remove the page from search results. If pages are found returning a status 400, your first step is determining if that page needs to be indexed in search results. If it should be indexed, the 400 response code is a critical error to address. If it is not a page that should be indexed, then the 400 status will help Google keep these pages out of rankings.

401403 Status Codes: Restrict Access

Both the 401 and 403 status codes can be used to indicate restricted access to a file or directory. By restricting access, you are telling robots from search engines not to index the page. The difference is that a 401 is about authentication while a 403 is about permission.

A 401 status code indicates authentication failed. For example, let’s say you have a password-protected area of your website. When a visitor (or robot) provides invalid login credentials, a 401 response status code says that proper credentials were not provided. A 401 can also be returned when invalid credentials are provided when connecting to an API. When used, a 401 must also include WWW-Authenticate in the response headers that specify the authentication methods (also known as challenges).

A 403 status code indicates the requested file or directory is forbidden because the person or robot making the request does not have permission to access the file. This is often used to block off large sections of the website that people and robots should not be able to view. For example, you would not want robots or people to see your entire image library, so the main page of the image library could return a 403 status code. This is what WordPress does by default, as you can see on my website:

It is important to not use a 401 or 403 to control crawling from robots. While a 401 or 403 will tell Google to not crawl the pages, they do not adjust how frequently Google will attempt to crawl the page. To control crawling, use a 429 status instead.

404410 Status Codes: Page Not Found

When the webpage is not found, the HTTP response status code should either be a 404 or 410. As mentioned above, you also want to watch out for Soft 404s too. For more about 404 vs. 410, Soft 404s, and other similar errors to check for on your website, see my guide to website error pages or learn how to fix 404 errors on your website.

429: Too Many Requests

A 429 response status code can be returned to tell a browser or robot that it is requesting too many files from the website and is overextending the server limits. This status code is used alongside rate limiting. Typically, this response code is not needed but can be useful on larger websites dealing with a high volume of requests.

Google recommends using this status code as part of emergency measures to limit crawls from Googlebot when Google’s crawls are harming website availability. The first step is to establish a method of detecting and responding dynamically if Googlebot is making too many requests. If Googlebot does make too many requests, approaching or exceeding the limit, the server should return a 429 response status code. If this status code is returned for more than a few days, it can permanently alter how frequently Google crawls the website.

5xx: Server Errors

The status code for any server error should be within the 5xx class. It is important to not return a status 200 with a server error because that tells robots the page is operating correctly. Similarly, returning a 404 with a server error confuses robots about what the error is. There are different types of 5xx response codes that can be returned:

  • A 500 response code is the most generic response code to use in the event of a server error. While generic, it still communicates that an error has occurred. Where possible, you want to use a more specific status code.
  • A 501 indicates that the server failed because the functionality requested is not available yet. This isn’t very commonly used and is not explicitly supported by Googlebot.
  • A 502 indicates the server received an invalid response. For example, Cloudflare received a request for a file but couldn’t fetch that file from the website’s server.
  • A 503 indicates the website is down for maintenance or is currently overloaded. This is the most common status code to use for server errors. You can also return a Retry-After header to indicate when the service will be returned (a Retry-After header is easier to return for planned maintenance when there is an established time window).
HTTP Status Codes Explained In 5 Minutes
HTTP Status Codes Explained In 5 Minutes

How to fix 404 errors

If you have seen the status code 404 Page Not found you might have been thinking “What does error 404 mean?”

HTTP status code 404 means “Page Not Found”. This means that the request you sent was received by the server, but it could not find the page you were looking for.

So to fix the 404 error you first need to find the cause for it, which can be due to many things. But since you know that the server is reachable (otherwise it would have returned a 5xx error), you know that the error is client-side. Basically that means it’s your fault (not as harsh as it sounds).

Luckily it means that you can also fix the error on your end without having to debugging your server or reaching out to your hosting provider.

Run through this checklist to fix the 404 error:

  1. Refresh the page. It might seem simple, but a 404 error could have just been a temporary issue that is fixed simply by trying again.
  2. Check the URL you typed in. Did you make a mistake somewhere? If the URL you typed is not exactly right a 404 is to be expected (unless a 3xx redirect is set up)
  3. If no mistake was made, try again from a different device like your mobile phone or tablet. If it works from a different device it’s most likely due to browser cache and cookies. Clear the browser cache and delete cookies, then try to access the page again.

If none of the above tricks worked, it’s likely that the piece of content was deleted or some other way moved. If the content was moved, which caused it to change URL, then you should make sure to set up a redirect that points from the old URL to the new one. That way you’re sure that anyone looking for the page can still find it.

If it was deleted, then a 404 error is the right response as the page truly was not found on your website and everything is working as it should.

If you see a lot of your visitors ending up on this page, then it’s most likely due to one of 3 things:

  1. You have an internal link on your website pointing to the page. If that’s the case, you should remove (or change) this link so it no longer points to a page that is not found.
  2. External websites link to the page. This is trickier as you can’t simply change it (although you can reach out to the websites and ask them to change it). A more simple thing for you to do would be to add a 301 redirect and point from the page to a different page on your website. That way you lead people to a page that is working, while also being a SEO-friendly option.
  3. The page is still showing up in Google’s search results and sending traffic to your website. While this is usually short-lived, it is possible that a 404 page can stay in the search results for a while, as a 404 does not tell Googlebot whether the page is temporarily or permanently missing. If this is happening, you’ll need to get the page back quickly or redirect it to a different page, so you won’t lose your rankings in Google.

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.

How to use PHP cURL to Handle JSON API Requests
How to use PHP cURL to Handle JSON API Requests

What does a 2xx Succesful status code mean?

A 2xx Succesful status code means that the request was successful and the browser has received the expected information. This is generally the one you want to see, as it means that the request was a success and has been received, understood and accepted it. As a website owner you should make sure that all pages and resources (images, videos, etc.) all return a 2xx status code. This means that browsers can reach it successfully and that your website visitors can see and use your website.

  • 200 OK
  • 201 Created
  • 202 Accepted
  • 203 Non-Authoritative Information
  • 204 No Content
  • 205 Reset Content
  • 206 Partial Content
  • 207 Multi-Status
  • 208 Already Reported
  • 226 IM Used

What does 200 OK mean?

The 200 OK status code means that the request was successful, but the meaning of success depends on the request method used:

  • GET: The requested resource has been fetched and transmitted to the message body.
  • HEAD: The header fields from the requested resource are sent in without the message body.
  • POST or PUT: A description of the result of the action is transmitted to the message body.
  • TRACE: The request messages, as received by the server, will be included in the message body

When looking at things SEO-wise the 200 OK response code is the perfect status code for a functioning page, all the linked pages are working as they should. A 200 will mean that search engine crawlers can successfully crawl the page and it will be put into their search index.

What does 201 Created mean?

The 201 Created status code means that the request was successfully fulfilled and resulted in one or possibly multiple new resources being created.

What does 202 Accepted mean?

The 202 Accepted status code means that the request has been accepted for processing, but the processing has not been finished yet. The request may or may not be completed when the processing eventually takes place.

What does 203 Non-Authoritative Information mean?

The 203 Non-Authoritative Information status code means that the request was successful. However, the meta-information that has been received is different from the one on the origin server and has instead been collected from a 3rd party or local copy. When not used for backups or mirrors of another resource a 200 OK response is preferable.

What does 204 No Content mean?

The 204 No Content status code means that while the server has successfully fulfilled the request, there is no available content for this request. But the user agent might want to update its currently cached headers for this resource, for the new one.

What does 205 Reset Content mean?

The 205 Reset Content status code means that the user should reset the document that sent this request.

What does 206 Partial Content mean?

The 206 Partial Content response code is a response to a Range header sent from the client when requesting only a part of the resource.

What does 207 Multi-Status mean?

The 207 Multi-Status status code conveys information about multiple resources, in situation when multiple status codes are appropriate.

What does 208 Already Reported mean?

The 208 Already Reported status code is used inside the response element DAV: propstat, in order to avoid enumerating the internal members of multiple bindings to the same collection repeatedly.

What does 226 IM Used mean?

The 226 IM response code means that the server has successfully fulfilled a GET request for the resource, and the response is a representation of the result of one or multiple instance-manipulations applied to the current instance.

Tip

To avoid errors and warnings in the case of bad status codes, you can place an @ in front of the file_get_contents so that this does not throw any errors.

/**
* 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 😉

Php basic : Tìm hiểu về GET và POST trong PHP qua ví dụ Form Submit - bài 5
Php basic : Tìm hiểu về GET và POST trong PHP qua ví dụ Form Submit – bài 5

What does a 4xx Client Error mean?

A 4xx Client Error status code means that the website or the page could not be reached and either the page is unavailable or the request contains bad syntax. As a website owner you should do your best to avoid these, as it means your users will not find what they’re looking for. This can be either pages that are no longer found and are either temporarily or permanently gone. Besides giving a bad user experience, it can also hurt your SEO efforts.

  • 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 Payload Too Large
  • 414 URI Too Long
  • 415 Unsupported Media Type
  • 416 Range Not Satisfiable
  • 417 Expectation Failed
  • 418 I’m a Teapot
  • 421 Misdirected Request
  • 422 Unprocessable Entity
  • 423 Locked
  • 424 Failed Dependency
  • 425 Too Early
  • 426 Upgrade Required
  • 428 Precondition Required
  • 429 Too Many Requests
  • 431 Request Header Fields Too Large
  • 451 Unavailable For Legal Reasons

What does 400 Bad Request mean?

The 400 Bad Request status code means that the server could not understand the request because of invalid syntax.

What does 401 Unauthorized mean?

The 401 Unauthorized status code means that the request has not been applied because the server requires user authentication.

What does 402 Payment Required mean?

The 402 Payment Required status code is a response reserved for future use. It was originally created to be implemented in digital payment systems, however, it is rarely used and a standard convention of using it does not exist.

What does 403 Forbidden mean?

The 403 Forbidden status code means that the client request has been rejected because the client does not have rights to access the content. Unlike a 401 error, the client’s identity is known to the server, but since they are not authorized to view the content, giving the proper response is rejected by the server.

What does error 404 mean?

The 404 Not Found status code means that the server either did not find a current representation for the requested resource or is trying to hide its existence from an unauthorized client.

When looking at things SEO-wise the 404 Not Found status code pages with a high volume of traffic should be redirected using a 301 to the most relevant page possible. For some pages, however, a 404 might be necessary, for example, if the product is out of stock for an extended period of time. If you have external links pointing to a page that returns 404, you will lose the link equity those links would otherwise give.

If you need to fix 404 errors, jump to this section.

What does 405 Method Not Allowed mean?

The 405 Method Not Allowed status code means that while the server knows the request method, the method has been disabled and can not be used.

What does 406 Not Acceptable mean?

The 406 Not Acceptable status code is sent by the server when it does not find any content following the criteria given by the user agent.

What does 407 Proxy Authentication Required mean?

The 407 Proxy Authentication Required status code means that the client must first be authenticated by a proxy (similar to a 401).

What does 408 Request Timeout mean?

The 408 Request Timeout status code means that the server did not receive a complete request in the time that it prepared to wait.

What does 409 Conflict mean?

The 409 Conflict status code means that the request could not be fulfilled due to a conflict with the current state of the target resource and is used in situations where the user might be able to resubmit the request after resolving the conflict.

What does 410 Gone mean?

The 410 Gone status code means that the target resource has been deleted and the condition seems to be permanent.

When looking at things SEO-wise the 410 Gone status code is a more permanent version a 404. The page will no longer be available from the server and has no forwarding address available. If you want to completely remove a page from Googles search index, then using 410 on a page is the proper way of doing it (instead of simply 404).

What does 411 Length Required mean?

The 411 Length Required status code means that the server has rejected the request because it requires the Content-Length header field to be defined.

What does 412 Precondition Failed mean?

The 412 Precondition Failed status code means the server does not meet one or multiple preconditions that were indicated in the request header fields.

What does 413 Payload Too Large mean?

The 413 Payload Too Large status code means the server refuses to process the request because the request payload is larger than the server is able or willing to process. While the server may close the connection to prevent the client from continuing the request, it should generate a Retry-After header field and after how long can the client retry.

What does 414 URI Too Long mean?

The 414 URI Too Long status code means that the server is refusing to service the request because the request-target was longer than the server was willing to interpret.

What does 415 Unsupported Media Type mean?

The 415 Unsupported Media Type status code means that the server is rejecting the request because it does not support the media format of the requested data.

What does 416 Range Not Satisfiable mean?

The 416 Range Not Satisfiable status code means that the range specified in the Range header field of the request can’t be fulfilled. The reason might be that the given range is outside the size of the target URI’s data.

What does 417 Expectation Failed mean?

The 417 Expectation Failed status code means that the Expectation indicated by the Expect request-header field could not be met by the server.

What does 418 I’m a Teapot mean?

The 418 I’m a Teapot status code means that the server refuses to brew coffee because it is, in fact, a teapot. (It is a reference to a 1998 April Fools’ joke called ”Hyper Text Coffee Pot Control Protocol”).

What does 421 Misdirected Request mean?

The 421 Misdirected Request status code means that the client request was directed at a server that is not configured to produce a response.

What does 422 Unprocessable Entity mean?

The 422 Unprocessable Entity status code means that while the request was well-formed, the server was unable to follow it, due to semantic errors.

What does 423 Locked mean?

The 423 Locked status code means that the resource that is being accessed is locked.

What does 424 Failed Dependency mean?

The 424 Failed Dependency status code means that the request failed due to the failure of a previous request.

What does 425 Too Early mean?

The 425 Too Early status code means that the server is not willing to risk processing a request that might be replayed.

What does 426 Upgrade Required mean?

The 426 Upgrade Required status code means that while the server refuses to perform the given request using the current protocol, it might be willing to do so after the client has been upgraded to a different protocol.

What does 428 Precondition Required mean?

The 428 Precondition Required status code means that the origin server requires the request to be conditional.

What does 429 Too Many Requests mean?

The 429 Too Many Requests response code means that in the given time, the user has sent too many requests.

What does 431 Request Header Fields Too Large mean?

The 431 Request Header Fields Too Large means that the server is not willing to process the request because its header fields are indeed too large, however, the request may be submitted again once the size of the request header fields is reduced.

What does 451 Unavailable For Legal Reasons mean?

The 451 Unavailable For Legal Reasons response code means that the user has requested an illegal resource (such as pages and sites blocked by the government).

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.

What are HTTP Status Codes - Complete Introduction | Https Tutorial
What are HTTP Status Codes – Complete Introduction | Https Tutorial

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 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.

42: How to Display Error Messages Using PHP | PHP Tutorial | Learn PHP Programming
42: How to Display Error Messages Using PHP | PHP Tutorial | Learn PHP Programming

How to check the HTTP status code of a page

Finding the server response code for a page can be done manually in your browser or by using various tools and website crawlers.

Depending on the browser you’re using it is slightly different. Below is how to do it in Chrome (most steps will be similar in other browsers).

Checking HTTP status code in Chrome

  1. Open the URL your want to check with your browser
  2. Open the Developer tab (F12) and go to the “Network” tab
  3. Refresh the page
  4. Scroll to the top of the list of requests and find the first of type “document”
  5. In “Status” you can now find the HTTP response code

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

How to Check HTTP Response Status Codes

By Matthew Edgar · Last Updated: January 19, 2024

Whenever you load a page or file on a website, the server hosting that website returns a numerical code that indicates the page’s status, called an HTTP Response Status Code. The status code says if the page is operating correctly, is in error, requires authentication, and more. The HTTP Response Status Code is returned as part of the HTTP Response Headers, which contains other details about the page.

You won’t see the HTTP Status Code displayed on the page itself. Instead, the server will return this response status code to the browser or robot requesting the page. The browser or robot will use that information to help load and process the page.

Several different response status codes can be returned. As an example, if the page loads successfully in response to a visitor’s request for that page, the website will return a response status code of 200. With that status code, browsers and robots know to load the page as usual. Alternatively, if the requested page is not found, the status code returned will be a 404. Browsers and robots know to handle this type of HTTP status code as an error page. If the requested page redirects elsewhere, the HTTP status code returned will be a 301 or 302. With a 301 or 302 status code, browsers and robots will process the redirect to a different URL.

In this article…

  • How to Check HTTP Response Status Codes
  • What HTTP Status Codes Are Returned by a Website?
  • Reviewing Specific Response Codes
  • Monitoring Status Code Usage
Real-Time Chat Application in PHP MySQL CodeIgniter with Source Code - CodeAstro
Real-Time Chat Application in PHP MySQL CodeIgniter with Source Code – CodeAstro

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.



<br /> php-generated 503<br />


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.


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.

Live notification using PHP & Pure JavaScript AJAX #PHP #liveNotification
Live notification using PHP & Pure JavaScript AJAX #PHP #liveNotification

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.

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.

HTTP Status Codes that should never have been created
HTTP Status Codes that should never have been created

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.


CURLINFO_CAINFO
Default built-in CA certificate path
CURLINFO_CAPATH
Default built-in CA path string
CURLINFO_EFFECTIVE_URL
Last effective URL
CURLINFO_HTTP_CODE
The last response code. As of cURL 7.10.8, this is a legacy alias of CURLINFO_RESPONSE_CODE
CURLINFO_FILETIME
Remote time of the retrieved document, with the CURLOPT_FILETIME enabled; if -1 is returned the time of the document is unknown
CURLINFO_TOTAL_TIME
Total transaction time in seconds for last transfer
CURLINFO_NAMELOOKUP_TIME
Time in seconds until name resolving was complete
CURLINFO_CONNECT_TIME
Time in seconds it took to establish the connection
CURLINFO_PRETRANSFER_TIME
Time in seconds from start until just before file transfer begins
CURLINFO_STARTTRANSFER_TIME
Time in seconds until the first byte is about to be transferred
CURLINFO_REDIRECT_COUNT
Number of redirects, with the CURLOPT_FOLLOWLOCATION option enabled
CURLINFO_REDIRECT_TIME
Time in seconds of all redirection steps before final transaction was started, with the CURLOPT_FOLLOWLOCATION option enabled
CURLINFO_REDIRECT_URL
With the CURLOPT_FOLLOWLOCATION option disabled: redirect URL found in the last transaction, that should be requested manually next. With the CURLOPT_FOLLOWLOCATION option enabled: this is empty. The redirect URL in this case is available in CURLINFO_EFFECTIVE_URL
CURLINFO_PRIMARY_IP
IP address of the most recent connection
CURLINFO_PRIMARY_PORT
Destination port of the most recent connection
CURLINFO_LOCAL_IP
Local (source) IP address of the most recent connection
CURLINFO_LOCAL_PORT
Local (source) port of the most recent connection
CURLINFO_SIZE_UPLOAD
Total number of bytes uploaded
CURLINFO_SIZE_DOWNLOAD
Total number of bytes downloaded
CURLINFO_SPEED_DOWNLOAD
Average download speed
CURLINFO_SPEED_UPLOAD
Average upload speed
CURLINFO_HEADER_SIZE
Total size of all headers received
CURLINFO_HEADER_OUT
The request string sent. For this to work, add the CURLINFO_HEADER_OUT option to the handle by calling curl_setopt()
CURLINFO_REFERER
The referrer header
CURLINFO_REQUEST_SIZE
Total size of issued requests, currently only for HTTP requests
CURLINFO_RETRY_AFTER
The information from the Retry-After: header, or zero if there was no valid header.
CURLINFO_SSL_VERIFYRESULT
Result of SSL certification verification requested by setting CURLOPT_SSL_VERIFYPEER
CURLINFO_CONTENT_LENGTH_DOWNLOAD
Content length of download, read from Content-Length: field
CURLINFO_CONTENT_LENGTH_UPLOAD
Specified size of upload
CURLINFO_CONTENT_TYPE
Content-Type: of the requested document. NULL indicates server did not send valid Content-Type: header
CURLINFO_PRIVATE
Private data associated with this cURL handle, previously set with the CURLOPT_PRIVATE option of curl_setopt()
CURLINFO_PROXY_ERROR
The detailed (SOCKS) proxy error code when the most recent transfer returned a CURLE_PROXY error. The returned value will be exactly one of the CURLPX_* values. The error code will be CURLPX_OK if no response code was available.
CURLINFO_RESPONSE_CODE
The last response code
CURLINFO_HTTP_CONNECTCODE
The CONNECT response code
CURLINFO_HTTPAUTH_AVAIL
Bitmask indicating the authentication method(s) available according to the previous response
CURLINFO_PROXYAUTH_AVAIL
Bitmask indicating the proxy authentication method(s) available according to the previous response
CURLINFO_OS_ERRNO
Errno from a connect failure. The number is OS and system specific.
CURLINFO_NUM_CONNECTS
Number of connections curl had to create to achieve the previous transfer
CURLINFO_SSL_ENGINES
OpenSSL crypto-engines supported
CURLINFO_COOKIELIST
All known cookies
CURLINFO_FTP_ENTRY_PATH
Entry path in FTP server
CURLINFO_APPCONNECT_TIME
Time in seconds it took from the start until the SSL/SSH connect/handshake to the remote host was completed
CURLINFO_CERTINFO
TLS certificate chain
CURLINFO_CONDITION_UNMET
Info on unmet time conditional
CURLINFO_RTSP_CLIENT_CSEQ
Next RTSP client CSeq
CURLINFO_RTSP_CSEQ_RECV
Recently received CSeq
CURLINFO_RTSP_SERVER_CSEQ
Next RTSP server CSeq
CURLINFO_RTSP_SESSION_ID
RTSP session ID
CURLINFO_CONTENT_LENGTH_DOWNLOAD_T
The content-length of the download. This is the value read from the Content-Length: field. -1 if the size isn’t known
CURLINFO_CONTENT_LENGTH_UPLOAD_T
The specified size of the upload. -1 if the size isn’t known
CURLINFO_HTTP_VERSION
The version used in the last HTTP connection. The return value will be one of the defined CURL_HTTP_VERSION_* constants or 0 if the version can’t be determined
CURLINFO_PROTOCOL
The protocol used in the last HTTP connection. The returned value will be exactly one of the CURLPROTO_* values
CURLINFO_PROXY_SSL_VERIFYRESULT
The result of the certificate verification that was requested (using the CURLOPT_PROXY_SSL_VERIFYPEER option). Only used for HTTPS proxies
CURLINFO_SCHEME
The URL scheme used for the most recent connection
CURLINFO_SIZE_DOWNLOAD_T
Total number of bytes that were downloaded. The number is only for the latest transfer and will be reset again for each new transfer
CURLINFO_SIZE_UPLOAD_T
Total number of bytes that were uploaded
CURLINFO_SPEED_DOWNLOAD_T
The average download speed in bytes/second that curl measured for the complete download
CURLINFO_SPEED_UPLOAD_T
The average upload speed in bytes/second that curl measured for the complete upload
CURLINFO_APPCONNECT_TIME_T
Time, in microseconds, it took from the start until the SSL/SSH connect/handshake to the remote host was completed
CURLINFO_CONNECT_TIME_T
Total time taken, in microseconds, from the start until the connection to the remote host (or proxy) was completed
CURLINFO_FILETIME_T
Remote time of the retrieved document (as Unix timestamp), an alternative to CURLINFO_FILETIME to allow systems with 32 bit long variables to extract dates outside of the 32bit timestamp range
CURLINFO_NAMELOOKUP_TIME_T
Time in microseconds from the start until the name resolving was completed
CURLINFO_PRETRANSFER_TIME_T
Time taken from the start until the file transfer is just about to begin, in microseconds
CURLINFO_REDIRECT_TIME_T
Total time, in microseconds, it took for all redirection steps include name lookup, connect, pretransfer and transfer before final transaction was started
CURLINFO_STARTTRANSFER_TIME_T
Time, in microseconds, it took from the start until the first byte is received
CURLINFO_TOTAL_TIME_T
Total time in microseconds for the previous transfer, including name resolving, TCP connect etc.

PHP – Get HTTP Response Status Code From a URL

This post shows you how to get the HTTP response status code from a URL. To do this, we will use get_headers built-in function, which returns an array with the headers in the HTTP response.

Exploring get_headers function

Let’s create a test to check what response headers we will get.


$url = 'https://bytenota.com'; $responseHeaders = get_headers($url, 1); print_r($responseHeaders);

And here is the result:


Array ( [0] => HTTP/1.0 200 OK [Content-Type] => text/html; charset=UTF-8 [Link] => ; rel="https://api.w.org/" [Date] => Tue, 19 Jun 2018 07:42:10 GMT [Accept-Ranges] => bytes [Server] => LiteSpeed [Alt-Svc] => quic=":443"; ma=2592000; v="35,37,38,39" [Connection] => close )

As you can see in the result, the HTTP response status code is in the first index value of the array (

HTTP/1.0 200 OK

).

The response status code can be:

  • HTTP/1.0 200 OK:
  • HTTP/1.0 301 Moved Permanently
  • HTTP/1.0 400 Bad Request
  • HTTP/1.0 404 Not Found
  • ect.

You can find the full list of response status code on this page.

Implementation


function getHTTPResponseStatusCode($url) { $status = null; $headers = @get_headers($url, 1); if (is_array($headers)) { $status = substr($headers[0], 9); } return $status; }

In the above code, we have implemented the function that returns an HTTP response status code only from given URL, i.e. we have removed

HTTP/1.0

string in the first index value of the array.

Usage

The below are two examples showing how to use the implemented function.

  • Example 1:


$url = 'https://bytenota.com'; $statusCode = getHTTPResponseStatusCode($url); echo $statusCode;

  • Output 1:


200 OK

  • Example 2:


$url = 'https://google.com/this-is-a-test'; $statusCode = getHTTPResponseStatusCode($url); echo $statusCode;

  • Output 2:


404 Not Found

How to get the status code of file_get_contents in PHP

The file_get_contents() function in PHP is pretty useful to easily request a resource from another server or locally.

Keep in mind that this only works for HTTP and HTTPS request and not when opening a file on your own system!

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.

Get Client IP Address & Detect VPN Connection In JavaScript, PHP & MySQL
Get Client IP Address & Detect VPN Connection In JavaScript, PHP & MySQL

What HTTP Status Codes Are Returned by a Website?

You can see all the HTTP status codes on Mozilla’s list, but there are only a few commonly seen HTTP status codes that you really need to understand. These are the HTTP status codes that have the greatest impact on UX and SEO:

  • 200 – Ok – the page is successfully loaded – normal
  • 201 – Created (see more details below)
  • 204 – No content
  • 301 – Permanent redirect
  • 302 – Temporary redirect (technically “Found”)
  • 304 – Not Modified (see more details below)
  • 307 – Temporary Redirect (learn more about 307 redirects)
  • 308 – Permanent Redirect (learn more about 308 redirects)
  • 400 – Bad Request (see more details below)
  • 401 – Unauthorized (invalid credentials, see more details below)
  • 403 – Forbidden (permission denied, see more details below)
  • 404 – Not Found
  • 406 – Not Acceptable
  • 410 – Gone/removed page
  • 429 – Too many requests (see more details below)
  • 451 – Unavailable For Legal Reasons
  • 500 – Internal server error (see details below)
  • 503 – Service unavailable (see details below)

Status Code Classes

The first digit in the status code represents the class of that status code. There are only five valid classes, 1 through 5. Sometimes the class is referred to with the first digit followed by “xx” values, such as 4xx or 5xx.

Class 1, or 1xx, are purely information status codes. These are seen in APIs but rarely used on websites.

Class 2, or 2xx, are used for successful requests. Status 200 is the most common of these.

Class 3, or 3xx, are used to instruct the browser or robot it needs to take further action to process the request. For example, a status 301 is used for a redirect and tells the browser or robot it needs to take further action to process the redirect.

Class 4, or 4xx, are used to tell the browser or robot that it has made a mistake with this request. After receiving the 4xx status code, the browser or robot needs to change how it interacts with the website. For example, a server sends a 404 to tell the browser or robot that the file it requested cannot be found and that it should stop requesting that page.

Class 5, or 5xx, are used to communicate server failures. The server received a valid request but could not respond. The different 5xx status codes indicate different types of problems and indicate how browsers or robots need to respond.

Why Check Status Codes

When you check your website’s response codes, you want to confirm the HTTP status code returned by every page on your website accurately reflects the nature of the page. If the nature of the page and the status code are in conflict, search robots can be confused by your website and that confusion will affect rankings and, ultimately, traffic.

The most common example of this status code versus page conflict is a Soft 404. With a Soft 404, the HTTP status code returned is 200, which would indicate everything is normal. However, with a Soft 404, the page content says the requested file could not be found. In this case, the HTTP status code should be a 404 to indicate the webpage is not found and to match the page’s content.

To begin identifying issues, like Soft 404s, that might exist on your website, the first step is to check the HTTP response code each page returns on your website.

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.

How to Check Network Status using JavaScript
How to Check Network Status using JavaScript

Monitoring Status Code Usage

It is also important to monitor what status codes Googlebot is encountering when crawling your website. One way to do this is in Google Search Console. In the sidebar, click on Settings, then under Crawling click on “Open Report”. On the main page, you can view crawling By Response. Clicking on any of the status codes will provide a list of pages that were returning that response code and the date of the last crawl.

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.

Create a Simple API In PHP with MySQL Database
Create a Simple API In PHP with MySQL Database

What does a 3xx Redirection code mean?

A 3xx Redirection status code means that you have been redirected and the completion of the request requires further action. Redirects are a natural part of the internet and you shouldn’t be scared to have 3xx redirect status codes on your website. A redirect means that the request was received successfully, but that the resource was found elsewhere. If a webpage has changed path and you try to access it through the old path, your CMS will often redirect the user to the new path. Ultimately the request will end in a 2xx success, but first it must go through the 3xx redirection.

  • 300 Multiple Choices
  • 301 Moved Permanently
  • 302 Found (Previously “Moved temporarily”)
  • 303 See Other
  • 304 Not Modified
  • 305 Use Proxy
  • 306 Switch Proxy
  • 307 Temporary Redirect
  • 308 Permanent Redirect

What does 300 Multiple Choices mean?

The 300 Multiple Choices status code means that the request has multiple possible responses and the user/user agent should choose one.

What does 301 Moved Permanently mean?

The 301 Moved Permanently response code means that the target resource has been assigned a new permanent URL and any references to this resources in the future should use one of the URLs included in the response.

When looking at things SEO-wise the 301 Permanent Redirect should be used every time a URL is moved permanently. This redirect passes your current link equity from your content to the new URL. Links that result in a status code 301 does give slightly less link equity than 200. So if you have a lot of links going through a 301 Permanent Redirect it is advised to fix these, if possible.

What does 302 Found (Previously “Moved temporarily”) mean?

The 302 Found status code, previously known as “Moved temporarily”, means that the URI of the request has been changed temporarily, and since changes can be made to the URI in the future, the effective request URI should be used for future requests.

When looking at things SEO-wise the 302 Found should only be used when making temporary changes as it does not pass the link equity the same way as a 301. If the page is not going to come back you should always use 301.

What does 303 See Other mean?

The 303 See Other response code is sent by the server in order to direct the client to get the requested resource at another URI with a GET request.

What does 304 Not Modified mean?

The 304 Not Modified response code informs the client that the response has not been modified. This means that the client can continue to use the already present, cached version of the response.

What does 305 Use Proxy mean?

The 305 Use Proxy status code instructs a client that it should connect to a proxy and then repeat the same request there. This response code is deprecated due to security concerns.

What does 306 Switch Proxy mean?

The 306 Switch proxy status code is no longer in use. It was used to inform the client that the subsequent requests should use the specified proxy.

What does 307 Temporary Redirect mean?

The 307 Temporary Redirect status code gets sent by the server in order to direct the client to the requested resource at another URI. The request method, however, must not be changed.

What does 308 Permanent Redirect mean?

The 308 Permanent Redirect status code means that the requested resource has been permanently assigned a new URI and future references to the resource should be made by using one of the enclosed URIs.

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");

How To Create A Simple REST API in PHP
How To Create A Simple REST API in PHP

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

(PHP 5 >= 5.4.0, PHP 7)

http_response_code — Get or Set the HTTP response code


$response_code] ) : mixed

Gets or sets the HTTP response status code.


response_code

The optional

response_code

will set the response code.

If

response_code

is provided, then the previous
status code will be returned. If

response_code

is not
provided, then the current status code will be returned. Both of these
values will default to a 200 status code if used in a web
server environment.


FALSE

will be returned if

response_code

is not
provided and it is not invoked in a web server environment (such as from a
CLI application).

TRUE

will be returned if

response_code

is provided and it is not invoked in a
web server environment (but only when no previous response status has been
set).

Example #1 Using http_response_code() in a web server environment



// Get the current response code and set a new onevar_dump(http_response_code(404));// Get the new response codevar_dump(http_response_code());?>

The above example will output:

int(200) int(404)

Example #2 Using http_response_code() in a CLI environment



// Get the current default response codevar_dump(http_response_code());// Set a response codevar_dump(http_response_code(201));// Get the new response codevar_dump(http_response_code());?>

The above example will output:

bool(false) bool(true) int(201)

  • 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

HTTP Status Codes & SEO: Here are the ones you need to know

If you want great results with your SEO it’s important to work with technical SEO. A big part of that is handling response codes on your website to ensure that the website is properly crawled by Googlebot and that your content returns the proper response code when it is requested.

Below are the 5 status codes that you need to know as an SEO.

200 OK & SEO

This is the goal for 99 % of your content (pages, media, etc.): a successful status code that means everything works like it should. This is critical to a well-functioning website and for a great user experience.

It also gives you the reassurance that all external pointing to your website will give you link value. If all of your content returns a 200 OK status code you can rest assured that your website is working and is properly accessible for crawlers and visitors alike.

301 Moved Permanently & SEO

In a perfect world all of your content will stay on the same URL and always respond with a 200 OK. But that’s rarely how it works in the real world when managing a website.

If a page has changed its URL you will need to set up a redirect to send users and bots from the old URL to the new URL. Otherwise they will be met by a 404 page (see explanation below). In some content management systems, automatic redirect is a built-in SEO feature, while in others you’ll have to manually set it up.

You should use 301 redirects if the page is permanently gone and will not come back. This is the case for pages that have changed their URL or content that has been deleted.

If something is gone, instead of simply moved, you can either let it become a 404 or choose to redirect it to something similar on your website. This could be a product that you’re no longer going to sell, where it can make sense to redirect that page to the category page instead.

302 Found & SEO

What if the page is only gone temporarily, but will come back again later? To give a good user experience you don’t want it to become a 404 page and you also don’t want to make a permanent 301 redirect.

The solution is to use 302 Found instead of a 301. To the user it will be the same, but to search engine crawlers and bots, it will tell them to check back later on, as this redirect is only temporary. That means the old URL will keep its value while it’s gone.

This is perfect for pages that will only be unavailable temporarily. An example could be a sold-out product which is removed from the website until it is back in stock. In that case you want to make use of a 302 Found temporary redirect. Once the product is back online, you remove the redirect and the page will have kept its value (and good rankings in search engines).

Note that if the 302 redirect is there for too long, Google will consider it a 301 permanent redirect instead.

404 Not Found & SEO

If a page is no longer found it will result in a 404 page (psst, here’s some tips on how to make a great 404 page). This means, that the server tells users, crawlers and bots that the page they were looking for is not found.

These are important to keep an eye on, as they can hurt your SEO a lot if not monitored and fixed.

Firstly, if a page returns a 404 it won’t be shown in Google’s search results. While it won’t get removed instantly, it will be after a short period of time, if not fixed. So if any of the pages that give you organic traffic end up returning a 404 error, you need to fix it quickly. See some tips on how to fix 404 errors here.

Secondly, if the page had any external links pointing to it, they will no longer give any value to your website. So even if the page does not receive any organic traffic, it can hurt your SEO performance.

The easiest way to fix this problem is to set up a 301 redirect. This will give a better user experience and will pass most of the link value from external links to the new page you’re redirecting to.

410 Gone & SEO

What if you actually want a page to completely disappear from Google’s search engine index? It might be intuitive to simply let it return a 404 error, but there’s one caveat with that:

404 does not tell crawlers and bots why the page was not found. For that reason, Google still might keep thinking that the page is there, even if it encounters a 404 error. In most cases this is fine, but there’s one case where you want to make it crystal clear that the content is gone. And that’s if you have been hacked and malicious content has been added to your website.

After doing cleanup it’s not enough to let the URLs return 404. Instead you should make sure that they return the 410 Gone status code. This clearly tells crawlers and bots that the page is gone for good and that they should remove it from their index.

5xx Server errors & SEO

The last one is not directly SEO-related, but more of a good tip for troubleshooting your website.

If you see any response code that start with 5xx, you should instantly know that it is a server error. This will help you greatly when it comes to troubleshooting and fixing it.

Instead of wasting time trying to fix the problem through your CMS backend or elsewhere, you can go straight to fixing the server. No matter if you do your own hosting or if you use a hosting provider, it is helpful to know that it’s related to the server, not your website.

PHP REST API CRUD 1: Create API in PHP to fetch data from database in php mysql | Database & Read
PHP REST API CRUD 1: Create API in PHP to fetch data from database in php mysql | Database & Read

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.

How are HTTP status codes categorized?

HTTP status codes are split into 5 different categories. Each category will give you hints as to what the response was, even if you don’t know the specific response code.

For an explanation of each category – and each individual status code – click on the corresponding link below or go to our complete list of HTTP status codes.

  • 1xx – Informational: The server has received the request and is continuing the process
  • 2xx – Successful: The request was successful and the browser has received the expected information
  • 3xx (Redirection): You have been redirected and the completion of the request requires further action
  • 4xx (Client Error): The website or the page could not be reached, either the page is unavailable or the request contains bad syntax
  • 5xx (Server Error): While the request appears to be valid, the server could not complete the request
How to detect and get user or client's IP address with PHP
How to detect and get user or client’s IP address with PHP

Find 404 pages in Google Analytics

Have you ever wondered if there’s a way to find 404 pages in Google Analytics?

Well, the good news is, there are ways to find them within your analytics setup. Now this can sometimes come down to how your website is configured. One way to find them is to check by page title – Your 404 page will very likely have “404” or “Page not found” in the title. It’s very easy to find the 404 page this way:

  • Within your analytics tool, go to behavior → Site Content → All Pages.
  • Now you can set your primary dimension to Page title and search for “404” or “Page not Found”.
  • And now – you should hopefully have your 404 report.

Now this is not the only way to set it up, but there is a very good chance that you can find the pages this way.

What does a 5xx Server error mean?

A 5xx Server error status code means that while the request appears to be valid, the server could not complete the request. If you’re experiencing 5xx server errors for your website, you should immediately look at your server. If you’re hosting your own server you’ll need to start debugging to figure out why it is not responding properly. If you’re using an external hosting provider you’ll need to reach out to them, so they can look at it.

  • 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
  • 510 Not Extended
  • 511 Network Authentication Required

What does 500 Internal Server Error mean?

The 500 Internal Server Error status code means that the server has encountered a situation that it does not know how to handle.

When looking at things SEO-wise the 500 Internal Server Error indicates a problem with the server, not the actual availability of the content. Since bots and users will both be lost, the link equity will go down fast.

What does 501 Not Implemented mean?

The 501 Not Implemented response code means that the request can not be handled because it is not supported by the server.

What does 502 Bad Gateway mean?

The 502 Bad Gateway response code means that the server received an invalid response while working as a gateway to handle the response.

What does 503 Service Unavailable mean?

The 503 Service Unavailable response code means that the server is currently not ready to handle the request. This is a common occurrence when the server is down for maintenance or is overloaded.

When looking at things SEO-wise the 503 Service Unavailable status code means that the server is unavailable and the visitor, bot or human, is asked to return again at a later time. This could be because of either server maintenance or server overload and search engines know to come back and check the availability later.

If you want to fix 503 errors, jump to this section.

What does 504 Gateway Timeout mean?

The 504 Gateway Timeout response code means that the server acting as a gateway could not get a response time.

What does 505 HTTP Version Not Supported mean?

The 505 HTTP Version Not Supported response code means that the version of HTTP used in the request is not supported by the server.

What does 506 Variant Also Negotiates mean?

The 506 Variant Also Negotiates response code means that the server has the following internal configuration error: The chosen variant resource is configured to engage in transparent negotiation itself, therefore it cannot be a proper endpoint in the negotiation process.

What does 507 Insufficient Storage mean?

The 507 Insufficient Storage status code means that the method could not be performed on the resource because the server is not able to store the representation that would be needed to complete the request successfully.

What does 508 Loop Detected mean?

The 508 Loop Detected response code means that the server has detected an infinite loop while processing the request.

What does 510 Not Extended mean?

The 510 Not Extended response code means that further extensions are required for the server to be able to fulfil the request.

What does 511 Network Authentication Required mean?

The 511 Network Authentication Required response code indicates that the client needs to authenticate to gain network access.

What are HTTP requests?
What are HTTP requests?

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.

How to Check HTTP Response Status Codes

There are several tools you can use to check the HTTP status codes your website’s pages currently return.

Simple Status Code Check: REDbot and WebSniffer

For a basic one-by-one analysis of a page, you can use a header check tool like REDbot. Enter the URL of the page you want to test then click the arrow button to fetch the page headers.

For a more advanced check, you can use WebSniffer to configure the request type, HTTP version, and the user-agent. It can be helpful to change the user agent to Googlebot to see what HTTP status codes are returned when Google is crawling the website.

In the returned response, we can locate the HTTP response status code in the HTTP Response Header. In this example, we can see that the requested URL returns an HTTP response status code of 301, indicating the URL has moved permanently. Within the response header, we can use “Location” to see where this URL redirects to—in this case, it redirects to https://www.matthewedgar.net. That means the non-secure HTTP version of this page redirects to the HTTPS (secure) version of this page. This is the expected behavior and, therefore, what we’d want to see here.

Check HTTP Status Code in Google Chrome Developer Tools

You can also check a page’s status code using Google Chrome’s Dev Tools.

To load Dev Tools, before opening a webpage, right click in Chrome and click “Inspect”. Once the Dev Tools area opens, click “Network” in the top bar. (Note that this may be hidden from view and you’ll find Network by clicking “>>”.) After opening up Network, load the webpage in Chrome.

You will see all of the resources needed for your page to load listed in the Network area. The first resource listed is the main page loaded. Click on that item and a new panel will appear. In this panel, you can see the status code of the requested page. In this example screenshot, you can see that my website’s homepage returns a status 200.

Here is another example, showing how you can see the status code of a redirect in Chrome Dev Tools. The redirected page is listed first and the redirect destination is listed second. In this example, the redirect returns a 301 status code, indicating a permanent redirect.

How To Check HTTP Status Codes In Bulk

Instead of checking an individual page at a time, you can also check several pages’ response codes at once using tools like HTTPStatus.

Alternatively, you can use a tool like Screaming Frog or Jet Octopus to check the response status as well. After running a crawl, you will see a list of all pages contained on your website and their respective status codes. Pay attention to any pages that don’t return a status 200.

Checking HTTP Status Code in JavaScript

Along with the tools discussed above, you can also obtain the HTTP status via code. Using JavaScript, you can get the HTTP status code of a URL via an XMLHttpRequest. You can see an implementation of that on this JSFiddle.

This code will not work on external domains or subdomains for security reasons. If you try to run this JavaScript code to check status codes on an external domain, you will get an “Access-Control-Allow-Origin” error message. That means you’ll have to run this code on the same domain but that can be helpful to check pages on your own website.

For example, to check a page on Elementive’s site, I’d have to run this code on Elementive’s domain and pass in relative URLs. To check the status code of the page https://example.com/page-url, I’d use the code:


getStatus('/page-url');

Checking HTTP Status Code in PHP

You can also check the page’s status code via PHP. This will work for the same domain and for (most) external domains. For example, this code will return the response status code for the stated URL (“HTTP/1.1 200 OK” in this example).


$url = 'https://www.elementive.com/';

$headers = get_headers($url, 1);echo($headers[0]);

PHP: How to Get Data from a Request | PHP get and post form methods
PHP: How to Get Data from a Request | PHP get and post form methods

How to fix 503 errors

The 503 response code means “Service Unavailable” and happens when a server is currently not ready to handle the request. This can be either due to the server being down for maintenance or if it is overloaded.

If this error occurs on your own website, you need to have a look at your server, as something is making it unable to process the requests made.

Unfortunately it’s not always easy and simple to fix. A 503 response code can be due to many things, but at least you know it’s server-related and not client-side like with a 404 error.

Here’s a list of steps you can go through to identify and fix a 503 error:

  1. Is your website still running and receiving traffic? Check your Analytics tools or server logs to see if other visitors are getting through to your website.
  2. If it’s no longer receiving traffic your server might be under maintenance or have crashed. If it’s under maintenance then a 503 is to be expected and everything will work fine once it’s done. If it crashed you should try restarting it.
  3. If you’re receiving huge amounts of website traffic, the server is most likely overloaded and returning 503 errors because it doesn’t have the resources to keep up. Before fixing such an issue you need to identify it the traffic is from real visitors or if you’re the victim of a DoS or DDoS attack.
  4. Identifying a DoS or DDoS attack can be hard, but the most effective ways are:

    1. Checking if one or more IP addresses make a lot of requests
    2. The TTL (time to live) on a ping request times out
    3. Analyzing the server logs and seeing huge spikes in traffic
  5. If it looks to be a DoS or DDoS attack, you’ll need to apply one or more defense techniques to stop the attack.
  6. If it is not a DoS or DDoS attack, then your website has most likely become more popular than your server can handle. The best way to fix such an issue is to look at connection limits, bandwidth throttling, system resources, fail-safes that might have triggered or anything that might be limiting server performance. Essentially you’ll need to upgrade your server so it has the proper resources to handle the traffic.

The above list is great for troubleshooting one-off 503 errors. But if it happens on a regular basis, then it might be a more permanent problem with your server that you should dive deeper into fixing. This can be inefficient processes using up all of your resources or your server simply not having enough allocated resources to handle the traffic your website is receiving.

Keywords searched by users: php get http status code

How To Correctly Return The Http Status Code 404 For An Error Page - Sistrix
How To Correctly Return The Http Status Code 404 For An Error Page – Sistrix
Http Get And Post Methods In Php - Geeksforgeeks
Http Get And Post Methods In Php – Geeksforgeeks
Which Http Status Code Should Use For Get, Post,Put, Delete,Patch Method |  204 For No Content - Youtube
Which Http Status Code Should Use For Get, Post,Put, Delete,Patch Method | 204 For No Content – Youtube
Create And Consume Simple Rest Api In Php | All Php Tricks
Create And Consume Simple Rest Api In Php | All Php Tricks
I Get A Null Response In My Php - Monday Apps & Developers - Monday  Community Forum
I Get A Null Response In My Php – Monday Apps & Developers – Monday Community Forum
Get Status Code From Api In Php In Minutes! - Youtube
Get Status Code From Api In Php In Minutes! – Youtube

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *