- $http_response_header
- Примеры
- User Contributed Notes 5 notes
- Send a 500 Internal Server Error header with PHP.
- Something went wrong!
- How To Return Status Codes In PHP
- 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
$http_response_header
Массив ( array ) $http_response_header похож на функцию get_headers() . При использовании обёртки HTTP, $http_response_header будет заполняться заголовками ответа HTTP. $http_response_header будет создан в локальной области видимости.
Примеры
Пример #1 Пример $http_response_header
function get_contents () file_get_contents ( «http://example.com» );
var_dump ( $http_response_header );
>
get_contents ();
var_dump ( $http_response_header );
?>?php
Результатом выполнения данного примера будет что-то подобное:
array(9) < [0]=>string(15) "HTTP/1.1 200 OK" [1]=> string(35) "Date: Sat, 12 Apr 2008 17:30:38 GMT" [2]=> string(29) "Server: Apache/2.2.3 (CentOS)" [3]=> string(44) "Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT" [4]=> string(27) "ETag: "280100-1b6-80bfd280"" [5]=> string(20) "Accept-Ranges: bytes" [6]=> string(19) "Content-Length: 438" [7]=> string(17) "Connection: close" [8]=> string(38) "Content-Type: text/html; charset=UTF-8" > NULL
User Contributed Notes 5 notes
Note that the HTTP wrapper has a hard limit of 1024 characters for the header lines.
Any HTTP header received that is longer than this will be ignored and won’t appear in $http_response_header.
The cURL extension doesn’t have this limit.
http_fopen_wrapper.c: #define HTTP_HEADER_BLOCK_SIZE 1024
parser function to get formatted headers (with response code)
function parseHeaders ( $headers )
$head = array();
foreach( $headers as $k => $v )
$t = explode ( ‘:’ , $v , 2 );
if( isset( $t [ 1 ] ) )
$head [ trim ( $t [ 0 ]) ] = trim ( $t [ 1 ] );
else
$head [] = $v ;
if( preg_match ( «#HTTP/[0-9\.]+\s+(9+)#» , $v , $out ) )
$head [ ‘reponse_code’ ] = intval ( $out [ 1 ]);
>
>
return $head ;
>
print_r ( parseHeaders ( $http_response_header ));
/*
Array
(
[0] => HTTP/1.1 200 OK
[reponse_code] => 200
[Date] => Fri, 01 May 2015 12:56:09 GMT
[Server] => Apache
[X-Powered-By] => PHP/5.3.3-7+squeeze18
[Set-Cookie] => PHPSESSID=ng25jekmlipl1smfscq7copdl3; path=/
[Expires] => Thu, 19 Nov 1981 08:52:00 GMT
[Cache-Control] => no-store, no-cache, must-revalidate, post-check=0, pre-check=0
[Pragma] => no-cache
[Vary] => Accept-Encoding
[Content-Length] => 872
[Connection] => close
[Content-Type] => text/html
)
*/
It seems that, if the server returns an HTTP/1.1 100 Continue, the variable $http_response_header is unset. This corner case may be difficult to be detected.
For this and other reasons I recommend PHP cURL, instead of file_get_contents().
If an HTTP Redirect is encountered, the headers will contain the response line and headers for all requests encountered. Consider this example:
array(23) [0]=>
string(18) «HTTP/1.1 302 FOUND»
[1]=>
string(17) «Connection: close»
[2]=>
string(22) «Server: meinheld/0.6.1»
[3]=>
string(35) «Date: Tue, 06 Feb 2018 11:21:21 GMT»
[4]=>
string(38) «Content-Type: text/html; charset=utf-8»
[5]=>
string(17) «Content-Length: 0»
[6]=>
string(30) «Location: https://httpbin.org/»
[7]=>
string(30) «Access-Control-Allow-Origin: *»
[8]=>
string(38) «Access-Control-Allow-Credentials: true»
[9]=>
string(19) «X-Powered-By: Flask»
[10]=>
string(34) «X-Processed-Time: 0.00107908248901»
[11]=>
string(14) «Via: 1.1 vegur»
[12]=>
string(15) «HTTP/1.1 200 OK»
[13]=>
string(17) «Connection: close»
[14]=>
string(22) «Server: meinheld/0.6.1»
[15]=>
string(35) «Date: Tue, 06 Feb 2018 11:21:21 GMT»
[16]=>
string(38) «Content-Type: text/html; charset=utf-8»
[17]=>
string(21) «Content-Length: 13011»
[18]=>
string(30) «Access-Control-Allow-Origin: *»
[19]=>
string(38) «Access-Control-Allow-Credentials: true»
[20]=>
string(19) «X-Powered-By: Flask»
[21]=>
string(34) «X-Processed-Time: 0.00848388671875»
[22]=>
string(14) «Via: 1.1 vegur»
>
Bear in mind this special variable is somehow protected and not populated in some situation when the peer server close the connection early on (ssl reset)
=> Undefined variable: http_response_header
Will return a cryptic error message:
Fatal error: Call to undefined function array() on line 2
—
Should you want to cope with this situation:
$hdrs = array(‘HTTP/1.1 400 Bad request’);
!empty($htp_response_header) && $hdrs = $http_response_headers;
Now use $hdrs in place of $http_response_header
Send a 500 Internal Server Error header with PHP.
This is a short guide on how to send a 500 Internal Server Error header to the client using PHP. This is useful because it allows us to tell the client that the server has encountered an unexpected condition and that it cannot fulfill the request.
Below, I have created a custom PHP function called internal_error.
//Function that sends a 500 Internal Server Error status code to //the client before killing the script. function internal_error()< header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500); echo 'Something went wrong!
'; exit; >
When the PHP function above is called, the script’s execution is halted and “Something went wrong!” is printed out onto the page.
Furthermore, if you inspect the HTTP headers with your browser’s developer console, you will see that the function is returning a 500 Internal Server Error status code:
Google’s Developer Tools showing the 500 Internal Server Error status that was returned.
To send the 500 status code, we used PHP’s header function like so:
//Send a 500 status code using PHP's header function header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500);
Note that we used the SERVER_PROTOCOL variable in this case because the client might be using HTTP 1.0 instead of HTTP 1.1. In other examples, you will find developers making the assumption that the client will always be using HTTP 1.1.
The problem with PHP is that it doesn’t always send a 500 Internal Server Error when an exception is thrown or a fatal error occurs.
This can cause a number of issues:
- It becomes more difficult to handle failed Ajax calls, as the server in question is still responding with a 200 OK status. For example: The JQuery Ajax error handling functions will not be called.
- Search engines such as Google may index your error pages. If this happens, your website may lose its rankings.
- Other HTTP clients might think that everything is A-OK when it is not.
Note that if you are using PHP version 5.4 or above, you can use the http_response_code function:
//Using http_response_code http_response_code(500);
How To Return Status Codes In PHP
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.
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.
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.
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.
HTTP Status Code Types – Overview
- 1xx informational response
- 2xx success
- 3xx redirection
- 4xx client errors
- 5xx server errors
- Unofficial status codes
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.
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.
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.
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.