You may use the following function to send a status change:
function header_status($statusCode) {
static $status_codes = null;
if ($status_codes === null) {
$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',
307 => 'Temporary 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',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
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',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended'
);
}
if ($status_codes[$statusCode] !== null) {
$status_string = $statusCode . ' ' . $status_codes[$statusCode];
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
}
}
You may use it as such:
<?php
header_status(500);
if (that_happened) {
die("that happened")
}
if (something_else_happened) {
die("something else happened")
}
update_database();
header_status(200);
mjt at jpeto dot net ¶
13 years ago
I strongly recommend, that you use
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
instead of
header("HTTP/1.1 404 Not Found");
I had big troubles with an Apache/2.0.59 (Unix) answering in HTTP/1.0 while I (accidentially) added a "HTTP/1.1 200 Ok" - Header.
Most of the pages were displayed correct, but on some of them apache added weird content to it:
A 4-digits HexCode on top of the page (before any output of my php script), seems to be some kind of checksum, because it changes from page to page and browser to browser. (same code for same page and browser)
"0" at the bottom of the page (after the complete output of my php script)
It took me quite a while to find out about the wrong protocol in the HTTP-header.
Marcel G ¶
13 years ago
Several times this one is asked on the net but an answer could not be found in the docs on php.net ...
If you want to redirect an user and tell him he will be redirected, e. g. "You will be redirected in about 5 secs. If not, click here." you cannot use header( 'Location: ...' ) as you can't sent any output before the headers are sent.
So, either you have to use the HTML meta refresh thingy or you use the following:
<?php
header( "refresh:5;url=wherever.php" );
echo 'You'll be redirected in about 5 secs. If not, click <a href="wherever.php">here</a>.';
?>
Hth someone
Dylan at WeDefy dot com ¶
15 years ago
A quick way to make redirects permanent or temporary is to make use of the $http_response_code parameter in header().
<?php
// 301 Moved Permanently
header("Location: /foo.php",TRUE,301);// 302 Found
header("Location: /foo.php",TRUE,302);
header("Location: /foo.php");// 303 See Other
header("Location: /foo.php",TRUE,303);// 307 Temporary Redirect
header("Location: /foo.php",TRUE,307);
?>
The HTTP status code changes the way browsers and robots handle redirects, so if you are using header(Location:) it's a good idea to set the status code at the same time. Browsers typically re-request a 307 page every time, cache a 302 page for the session, and cache a 301 page for longer, or even indefinitely. Search engines typically transfer "page rank" to the new location for 301 redirects, but not for 302, 303 or 307. If the status code is not specified, header('Location:') defaults to 302.
mandor at mandor dot net ¶
17 years ago
When using PHP to output an image, it won't be cached by the client so if you don't want them to download the image each time they reload the page, you will need to emulate part of the HTTP protocol.
Here's how:
<?php// Test image.
$fn = '/test/foo.png';// Getting headers sent by the client.
$headers = apache_request_headers(); // Checking if the client is validating his cache and if it is current.
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
header('Content-Length: '.filesize($fn));
header('Content-Type: image/png');
print file_get_contents($fn);
}?>
That way foo.png will be properly cached by the client and you'll save bandwith. :)
bebertjean at yahoo dot fr ¶
14 years ago
If using the 'header' function for the downloading of files, especially if you're passing the filename as a variable, remember to surround the filename with double quotes, otherwise you'll have problems in Firefox as soon as there's a space in the filename.
So instead of typing:
<?php
header("Content-Disposition: attachment; filename=" . basename($filename));
?>
you should type:
<?php
header("Content-Disposition: attachment; filename="" . basename($filename) . """);
?>
If you don't do this then when the user clicks on the link for a file named "Example file with spaces.txt", then Firefox's Save As dialog box will give it the name "Example", and it will have no extension.
See the page called "Filenames_with_spaces_are_truncated_upon_download" at
http://kb.mozillazine.org/ for more information. (Sorry, the site won't let me post such a long link...)
php at ober-mail dot de ¶
3 years ago
Since PHP 5.4, the function `http_response_code()` can be used to set the response code instead of using the `header()` function, which requires to also set the correct protocol version (which can lead to problems, as seen in other comments).
tim at sharpwebdevelopment dot com ¶
5 years ago
The header call can be misleading to novice php users.
when "header call" is stated, it refers the the top leftmost position of the file and not the "header()" function itself.
"<?php" opening tag must be placed before anything else, even whitespace.
sk89q ¶
14 years ago
You can use HTTP's etags and last modified dates to ensure that you're not sending the browser data it already has cached.
<?php
$last_modified_time = filemtime($file);
$etag = md5_file($file);
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT");
header("Etag: $etag");
if (@
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time ||
trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
?>
yjf_victor ¶
7 years ago
According to the RFC 6226 (https://tools.ietf.org/html/rfc6266), the only way to send Content-Disposition Header with encoding is:
Content-Disposition: attachment;
filename*= UTF-8''%e2%82%ac%20rates
for backward compatibility, what should be sent is:
Content-Disposition: attachment;
filename="EURO rates";
filename*=utf-8''%e2%82%ac%20rates
As a result, we should use
<?php
$filename = '中文文件名.exe'; // a filename in Chinese characters$contentDispositionField = 'Content-Disposition: attachment; '
. sprintf('filename="%s"; ', rawurlencode($filename))
. sprintf("filename*=utf-8''%s", rawurlencode($filename));header('Content-Type: application/octet-stream');header($contentDispositionField);readfile('file_to_download.exe');
?>
I have tested the code in IE6-10, firefox and Chrome.
David Spector ¶
1 year ago
Please note that there is no error checking for the header command, either in PHP, browsers, or Web Developer Tools.
If you use something like "header('text/javascript');" to set the MIME type for PHP response text (such as for echoed or Included data), you will get an undiagnosed failure.
The proper MIME-setting function is "header('Content-type: text/javascript');".
David ¶
5 years ago
It seems the note saying the URI must be absolute is obsolete. Found on https://en.wikipedia.org/wiki/HTTP_location
«An obsolete version of the HTTP 1.1 specifications (IETF RFC 2616) required a complete absolute URI for redirection.[2] The IETF HTTP working group found that the most popular web browsers tolerate the passing of a relative URL[3] and, consequently, the updated HTTP 1.1 specifications (IETF RFC 7231) relaxed the original constraint, allowing the use of relative URLs in Location headers.»
nospam at nospam dot com ¶
7 years ago
<?php// Response codes behaviors when using
header('Location: /target.php', true, $code) to forward user to another page:$code = 301;
// Use when the old page has been "permanently moved and any future requests should be sent to the target page instead. PageRank may be transferred."$code = 302; (default)
// "Temporary redirect so page is only cached if indicated by a Cache-Control or Expires header field."$code = 303;
// "This method exists primarily to allow the output of a POST-activated script to redirect the user agent to a selected resource. The new URI is not a substitute reference for the originally requested resource and is not cached."$code = 307;
// Beware that when used after a form is submitted using POST, it would carry over the posted values to the next page, such if target.php contains a form processing script, it will process the submitted info again!
// In other words, use 301 if permanent, 302 if temporary, and 303 if a results page from a submitted form.
// Maybe use 307 if a form processing script has moved.
?>
jp at webgraphe dot com ¶
19 years ago
A call to session_write_close() before the statement
<?php
header("Location: URL");
exit();
?>
is recommended if you want to be sure the session is updated before proceeding to the redirection.
We encountered a situation where the script accessed by the redirection wasn't loading the session correctly because the precedent script hadn't the time to update it (we used a database handler).
JP.
ben at indietorrent dot org ¶
11 years ago
Be aware that sending binary files to the user-agent (browser) over an encrypted connection (SSL/TLS) will fail in IE (Internet Explorer) versions 5, 6, 7, and 8 if any of the following headers is included:
Cache-control:no-store
Cache-control:no-cache
See: http://support.microsoft.com/kb/323308
Workaround: do not send those headers.
Also, be aware that IE versions 5, 6, 7, and 8 double-compress already-compressed files and do not reverse the process correctly, so ZIP files and similar are corrupted on download.
Workaround: disable compression (beyond text/html) for these particular versions of IE, e.g., using Apache's "BrowserMatch" directive. The following example disables compression in all versions of IE:
BrowserMatch ".*MSIE.*" gzip-only-text/html
chris at ocproducts dot com ¶
6 years ago
Note that 'session_start' may overwrite your custom cache headers.
To remedy this you need to call:
session_cache_limiter('');
...after you set your custom cache headers. It will tell the PHP session code to not do any cache header changes of its own.
shutout2730 at yahoo dot com ¶
14 years ago
It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.
This redirects to 2.html since the second header replaces the first.
<?php
header("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>
This redirects to 1.html since the header is sent as soon as the echo happens. You also won't see any "headers already sent" errors because the browser follows the redirect before it can display the error.
<?php
header("location: 1.html");
echo "send data";
header("location: 2.html"); //1.html already sent
?>
Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren't sent until the output buffer is flushed.
<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>
dev at omikrosys dot com ¶
13 years ago
Just to inform you all, do not get confused between Content-Transfer-Encoding and Content-Encoding
Content-Transfer-Encoding specifies the encoding used to transfer the data within the HTTP protocol, like raw binary or base64. (binary is more compact than base64. base64 having 33% overhead).
Eg Use:- header('Content-Transfer-Encoding: binary');
Content-Encoding is used to apply things like gzip compression to the content/data.
Eg Use:- header('Content-Encoding: gzip');
Emmanuel Chazard ¶
1 day ago
If you use header() to allow the user to download a file, it's very important to check the encoding of the script itself. Your script should be encoded in UTF-8, but definitely not in UTF-8-BOM! The presence of BOM will alter the file received by the user. Let the following script:
<?php
$content
= file_get_contents('test_download.png') ;
$name = 'test.png' ;
$size = strlen($content) ;header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');
header('Content-Disposition: attachment; filename="'.$name.'"');
header('Content-Length: ' . $size);
header('Pragma: public');
echo
$content ;?>
Irrespectively from the encoding of test_download.png, when this PHP script is encoded in UTF-8-BOM, the content received by the user is different:
- a ZWNBSP byte (U+FEFF) is added to the beginning of the file
- the file content is truncated!!!
If it's a binary file (e.g. image, proprietary format), the file will become unreadable.
mzheng[no-spam-thx] at ariba dot com ¶
14 years ago
For large files (100+ MBs), I found that it is essential to flush the file content ASAP, otherwise the download dialog doesn't show until a long time or never.
<?php
header("Content-Disposition: attachment; filename=" . urlencode($file));
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Description: File Transfer");
header("Content-Length: " . filesize($file));
flush(); // this doesn't really matter.$fp = fopen($file, "r");
while (!feof($fp))
{
echo fread($fp, 65536);
flush(); // this is essential for large downloads
}
fclose($fp);
?>
razvan_bc at yahoo dot com ¶
5 years ago
<?php
/* This will give an error. Note the output
* above, which is before the header() call */
header('Location: http://www.example.com/');
exit;
?>
this example is pretty good BUT in time you use "exit" the parser will still work to decide what's happening next the "exit" 's action should do ('cause if you check the manual exit works in others situations too).
SO MY POINT IS : you should use :
<?php
header
('Location: http://www.example.com/');
die();?>
'CAUSE all die function does is to stop the script ,there is no other place for interpretation and the scope you choose to break the action of your script is quickly DONE!!!
there are many situations with others examples and the right choose for small parts of your scrips that make differences when you write your php framework at well!
Thanks Rasmus Lerdorf and his team to wrap off parts of unusual php functionality ,php 7 roolez!!!!!
scott at lucentminds dot com ¶
13 years ago
If you want to remove a header and keep it from being sent as part of the header response, just provide nothing as the header value after the header name. For example...
PHP, by default, always returns the following header:
"Content-Type: text/html"
Which your entire header response will look like
HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
If you call the header name with no value like so...
<?php
header
( 'Content-Type:' );?>
Your headers now look like this:
HTTP/1.1 200 OK
Server: Apache/2.2.11 (Unix)
X-Powered-By: PHP/5.2.8
Date: Fri, 16 Oct 2009 23:05:07 GMT
Connection: close
Cody G. ¶
12 years ago
After lots of research and testing, I'd like to share my findings about my problems with Internet Explorer and file downloads.
Take a look at this code, which replicates the normal download of a Javascript:
<?php
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Content-type: text/javascript");
header("Content-Disposition: inline; filename="download.js"");
header("Content-Length: ".filesize("my-file.js"));
} else {
header("Content-type: application/force-download");
header("Content-Disposition: attachment; filename="download.js"");
header("Content-Length: ".filesize("my-file.js"));
}
header("Expires: Fri, 01 Jan 2010 05:00:00 GMT");
if(strstr($_SERVER["HTTP_USER_AGENT"],"MSIE")==false) {
header("Cache-Control: no-cache");
header("Pragma: no-cache");
}
include("my-file.js");
?>
Now let me explain:
I start out by checking for IE, then if not IE, I set Content-type (case-sensitive) to JS and set Content-Disposition (every header is case-sensitive from now on) to inline, because most browsers outside of IE like to display JS inline. (User may change settings). The Content-Length header is required by some browsers to activate download box. Then, if it is IE, the "application/force-download" Content-type is sometimes required to show the download box. Use this if you don't want your PDF to display in the browser (in IE). I use it here to make sure the box opens. Anyway, I set the Content-Disposition to attachment because I already know that the box will appear. Then I have the Content-Length again.
Now, here's my big point. I have the Cache-Control and Pragma headers sent only if not IE. THESE HEADERS WILL PREVENT DOWNLOAD ON IE!!! Only use the Expires header, after all, it will require the file to be downloaded again the next time. This is not a bug! IE stores downloads in the Temporary Internet Files folder until the download is complete. I know this because once I downloaded a huge file to My Documents, but the Download Dialog box put it in the Temp folder and moved it at the end. Just think about it. If IE requires the file to be downloaded to the Temp folder, setting the Cache-Control and Pragma headers will cause an error!
I hope this saves someone some time!
~Cody G.
Vinay Kotekar ¶
8 years ago
Saving php file in ANSI no isuess but when saving the file in UTF-8 format for various reasons remember to save the file without any BOM ( byte-order mark) support.
Otherwise you will face problem of headers not being properly sent
eg.
<?php header("Set-Cookie: name=user");?>
Would give something like this :-
Warning: Cannot modify header information - headers already sent by (output started at C:wwwinfo.php:1) in C:wwwinfo.php on line 1
Angelica Perduta ¶
3 years ago
I made a script that generates an optimized image for use on web pages using a 404 script to resize and reduce original images, but on some servers it was generating the image but then not using it due to some kind of cache somewhere of the 404 status. I managed to get it to work with the following and although I don't quite understand it, I hope my posting here does help others with similar issues:
header_remove();
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
// ... and then try redirecting
// 201 = The request has been fulfilled, resulting in the creation of a new resource however it's still not loading
// 302 "moved temporarily" does seems to load it!
header("location:$dst", FALSE, 302); // redirect to the file now we have it
Refugnic ¶
13 years ago
My files are in a compressed state (bz2). When the user clicks the link, I want them to get the uncompressed version of the file.
After decompressing the file, I ran into the problem, that the download dialog would always pop up, even when I told the dialog to 'Always perform this operation with this file type'.
As I found out, the problem was in the header directive 'Content-Disposition', namely the 'attachment' directive.
If you want your browser to simulate a plain link to a file, either change 'attachment' to 'inline' or omit it alltogether and you'll be fine.
This took me a while to figure out and I hope it will help someone else out there, who runs into the same problem.
Anonymous ¶
13 years ago
I just want to add, becuase I see here lots of wrong formated headers.
1. All used headers have first letters uppercase, so you MUST follow this. For example:
Location, not location
Content-Type, not content-type, nor CONTENT-TYPE
2. Then there MUST be colon and space, like
good: header("Content-Type: text/plain");
wrong: header("Content-Type:text/plain");
3. Location header MUST be absolute uri with scheme, domain, port, path, etc.
good: header("Location: http://www.example.com/something.php?a=1");
4. Relative URIs are NOT allowed
wrong: Location: /something.php?a=1
wrong: Location: ?a=1
It will make proxy server and http clients happier.
bMindful at fleetingiamge dot org ¶
20 years ago
If you haven't used, HTTP Response 204 can be very convenient. 204 tells the server to immediately termiante this request. This is helpful if you want a javascript (or similar) client-side function to execute a server-side function without refreshing or changing the current webpage. Great for updating database, setting global variables, etc.
header("status: 204"); (or the other call)
header("HTTP/1.0 204 No Response");
nobileelpirata at hotmail dot com ¶
16 years ago
This is the Headers to force a browser to use fresh content (no caching) in HTTP/1.0 and HTTP/1.1:
<?PHP
header( 'Expires: Sat, 26 Jul 1997 05:00:00 GMT' );
header( 'Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
?>
er dot ellison dot nyc at gmail dot com ¶
7 years ago
DO NOT PUT space between location and the colon that comes after that ,
// DO NOT USE THIS :
header("Location : #whatever"); // -> will not work !
// INSTEAD USE THIS ->
header("Location: #wahtever"); // -> will work forever !
jamie ¶
14 years ago
The encoding of a file is discovered by the Content-Type, either in the HTML meta tag or as part of the HTTP header. Thus, the server and browser does not need - nor expect - a Unicode file to begin with a BOM mark. BOMs can confuse *nix systems too. More info at http://unicode.org/faq/utf_bom.html#bom1
On another note: Safari can display CMYK images (at least the OS X version, because it uses the services of QuickTime)
ASchmidt at Anamera dot net ¶
5 years ago
Setting the "Location: " header has another undocumented side-effect!
It will also disregard any expressly set "Content-Type: " and forces:
"Content-Type: text/html; charset=UTF-8"
The HTTP RFCs don't call for such a drastic action. They simply state that a redirect content SHOULD include a link to the destination page (in which case ANY HTML compatible content type would do). But PHP even overrides a perfectly standards-compliant
"Content-Type: application/xhtml+xml"!
hamza dot eljaouhari dot etudes at gmail dot com ¶
5 years ago
// Beware that adding a space between the keyword "Location" and the colon causes an Internal Sever Error
//This line causes the error
7
header('Location : index.php&controller=produit&action=index');
// While It must be written without the space
header('Location: index.php&controller=produit&action=index');
cedric at gn dot apc dot org ¶
12 years ago
Setting a Location header "returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set". If you are sending a response to a POST request, you might want to look at RFC 2616 sections 10.3.3 and 10.3.4. It is suggested that if you want the browser to immediately GET the resource in the Location header in this circumstance, you should use a 303 status code not the 302 (with the same link as hypertext in the body for very old browsers). This may have (rare) consequences as mentioned in bug 42969.
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 '<h1>Something went wrong!</h1>'; 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.
This is not the case.
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);
Far more concise!
Содержание
- Send a 500 Internal Server Error header with PHP.
- http_response_code
- Description
- Parameters
- Return Values
- Examples
- See Also
- User Contributed Notes 18 notes
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.
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:
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.
This is not the case.
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:
Источник
http_response_code
(PHP 5 >= 5.4.0, PHP 7, PHP
http_response_code — Get or Set the HTTP response code
Description
Gets or sets the HTTP response status code.
Parameters
The optional response_code will set the response code.
Return Values
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).
Examples
Example #1 Using http_response_code() in a web server environment
// Get the current response code and set a new one
var_dump ( http_response_code ( 404 ));
// Get the new response code
var_dump ( http_response_code ());
?>
The above example will output:
Example #2 Using http_response_code() in a CLI environment
// Get the current default response code
var_dump ( http_response_code ());
// Set a response code
var_dump ( http_response_code ( 201 ));
// Get the new response code
var_dump ( http_response_code ());
?>
The above example will output:
See Also
- header() — Send a raw HTTP header
- headers_list() — Returns a list of response headers sent (or ready to send)
User Contributed Notes 18 notes
If your version of PHP does not include this function:
if (! function_exists ( ‘http_response_code’ )) <
function http_response_code ( $code = NULL ) <
switch ( $code ) <
case 100 : $text = ‘Continue’ ; break;
case 101 : $text = ‘Switching Protocols’ ; break;
case 200 : $text = ‘OK’ ; break;
case 201 : $text = ‘Created’ ; break;
case 202 : $text = ‘Accepted’ ; break;
case 203 : $text = ‘Non-Authoritative Information’ ; break;
case 204 : $text = ‘No Content’ ; break;
case 205 : $text = ‘Reset Content’ ; break;
case 206 : $text = ‘Partial Content’ ; break;
case 300 : $text = ‘Multiple Choices’ ; break;
case 301 : $text = ‘Moved Permanently’ ; break;
case 302 : $text = ‘Moved Temporarily’ ; break;
case 303 : $text = ‘See Other’ ; break;
case 304 : $text = ‘Not Modified’ ; break;
case 305 : $text = ‘Use Proxy’ ; break;
case 400 : $text = ‘Bad Request’ ; break;
case 401 : $text = ‘Unauthorized’ ; break;
case 402 : $text = ‘Payment Required’ ; break;
case 403 : $text = ‘Forbidden’ ; break;
case 404 : $text = ‘Not Found’ ; break;
case 405 : $text = ‘Method Not Allowed’ ; break;
case 406 : $text = ‘Not Acceptable’ ; break;
case 407 : $text = ‘Proxy Authentication Required’ ; break;
case 408 : $text = ‘Request Time-out’ ; break;
case 409 : $text = ‘Conflict’ ; break;
case 410 : $text = ‘Gone’ ; break;
case 411 : $text = ‘Length Required’ ; break;
case 412 : $text = ‘Precondition Failed’ ; break;
case 413 : $text = ‘Request Entity Too Large’ ; break;
case 414 : $text = ‘Request-URI Too Large’ ; break;
case 415 : $text = ‘Unsupported Media Type’ ; break;
case 500 : $text = ‘Internal Server Error’ ; break;
case 501 : $text = ‘Not Implemented’ ; break;
case 502 : $text = ‘Bad Gateway’ ; break;
case 503 : $text = ‘Service Unavailable’ ; break;
case 504 : $text = ‘Gateway Time-out’ ; break;
case 505 : $text = ‘HTTP Version not supported’ ; break;
default:
exit( ‘Unknown http status code «‘ . htmlentities ( $code ) . ‘»‘ );
break;
>
$protocol = (isset( $_SERVER [ ‘SERVER_PROTOCOL’ ]) ? $_SERVER [ ‘SERVER_PROTOCOL’ ] : ‘HTTP/1.0’ );
header ( $protocol . ‘ ‘ . $code . ‘ ‘ . $text );
$GLOBALS [ ‘http_response_code’ ] = $code ;
$code = (isset( $GLOBALS [ ‘http_response_code’ ]) ? $GLOBALS [ ‘http_response_code’ ] : 200 );
?>
In this example I am using $GLOBALS, but you can use whatever storage mechanism you like. I don’t think there is a way to return the current status code:
For reference the error codes I got from PHP’s source code:
And how the current http header is sent, with the variables it uses:
Note that you can NOT set arbitrary response codes with this function, only those that are known to PHP (or the SAPI PHP is running on).
The following codes currently work as expected (with PHP running as Apache module):
200 – 208, 226
300 – 305, 307, 308
400 – 417, 422 – 424, 426, 428 – 429, 431
500 – 508, 510 – 511
Codes 0, 100, 101, and 102 will be sent as «200 OK».
Everything else will result in «500 Internal Server Error».
If you want to send responses with a freestyle status line, you need to use the `header()` function:
( «HTTP/1.0 418 I’m A Teapot» ); ?>
When setting the response code to non-standard ones like 420, Apache outputs 500 Internal Server Error.
This happens when using header(0,0,420) and http_response_code(420).
Use header(‘HTTP/1.1 420 Enhance Your Calm’) instead.
Note that the response code in the string IS interpreted and used in the access log and output via http_response_code().
Status codes as an array:
= 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»
Do not mix the use of http_response_code() and manually setting the response code header because the actual HTTP status code being returned by the web server may not end up as expected. http_response_code() does not work if the response code has previously been set using the header() function. Example:
( ‘HTTP/1.1 401 Unauthorized’ );
http_response_code ( 403 );
print( http_response_code ());
?>
The raw HTTP response will be (notice the actual status code on the first line does not match the printed http_response_code in the body):
HTTP/1.1 401 Unauthorized
Date: Tue, 24 Nov 2020 13:49:08 GMT
Server: Apache
Connection: Upgrade, Keep-Alive
Keep-Alive: timeout=5, max=100
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
I only tested it on Apache. I am not sure if this behavior is specific to Apache or common to all PHP distributions.
You can also create a enum by extending the SplEnum class.
/** HTTP status codes */
class HttpStatusCode extends SplEnum <
const __default = self :: OK ;
const SWITCHING_PROTOCOLS = 101 ;
const OK = 200 ;
const CREATED = 201 ;
const ACCEPTED = 202 ;
const NONAUTHORITATIVE_INFORMATION = 203 ;
const NO_CONTENT = 204 ;
const RESET_CONTENT = 205 ;
const PARTIAL_CONTENT = 206 ;
const MULTIPLE_CHOICES = 300 ;
const MOVED_PERMANENTLY = 301 ;
const MOVED_TEMPORARILY = 302 ;
const SEE_OTHER = 303 ;
const NOT_MODIFIED = 304 ;
const USE_PROXY = 305 ;
const BAD_REQUEST = 400 ;
const UNAUTHORIZED = 401 ;
const PAYMENT_REQUIRED = 402 ;
const FORBIDDEN = 403 ;
const NOT_FOUND = 404 ;
const METHOD_NOT_ALLOWED = 405 ;
const NOT_ACCEPTABLE = 406 ;
const PROXY_AUTHENTICATION_REQUIRED = 407 ;
const REQUEST_TIMEOUT = 408 ;
const CONFLICT = 408 ;
const GONE = 410 ;
const LENGTH_REQUIRED = 411 ;
const PRECONDITION_FAILED = 412 ;
const REQUEST_ENTITY_TOO_LARGE = 413 ;
const REQUESTURI_TOO_LARGE = 414 ;
const UNSUPPORTED_MEDIA_TYPE = 415 ;
const REQUESTED_RANGE_NOT_SATISFIABLE = 416 ;
const EXPECTATION_FAILED = 417 ;
const IM_A_TEAPOT = 418 ;
const INTERNAL_SERVER_ERROR = 500 ;
const NOT_IMPLEMENTED = 501 ;
const BAD_GATEWAY = 502 ;
const SERVICE_UNAVAILABLE = 503 ;
const GATEWAY_TIMEOUT = 504 ;
const HTTP_VERSION_NOT_SUPPORTED = 505 ;
>
if you need a response code not supported by http_response_code(), such as WebDAV / RFC4918’s «HTTP 507 Insufficient Storage», try:
( $_SERVER [ ‘SERVER_PROTOCOL’ ] . ‘ 507 Insufficient Storage’ );
?>
result: something like
HTTP/1.1 507 Insufficient Storage
The note above from «Anonymous» is wrong. I’m running this behind the AWS Elastic Loadbalancer and trying the header(‘:’.$error_code. ) method mentioned above is treated as invalid HTTP.
The documentation for the header() function has the right way to implement this if you’re still on ( «HTTP/1.0 404 Not Found» );
?>
At least on my side with php-fpm and nginx this method does not change the text in the response, only the code.
// HTTP/1.1 404 Not Found
http_response_code ( 404 );
?>
The resulting response is HTTP/1.1 404 OK
http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h. Note that this means your response code must match a response code that PHP knows about. You can’t create your own response codes using this method, however you can using the header method.
In summary — The differences between «http_response_code» and «header» for setting response codes:
1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.
2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can’t set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header method.
It’s not mentioned explicitly, but the return value when SETTING, is the OLD status code.
e.g.
= http_response_code ();
$b = http_response_code ( 202 );
$c = http_response_code ();
var_dump ( $a , $b , $c );
http_response_code() does not actually send HTTP headers, it only prepares the header list to be sent later on.
So you can call http_reponse_code() to set, get and reset the HTTP response code before it gets sent.
http_response_code(500); // set the code
var_dump(headers_sent()); // check if headers are sent
http_response_code(200); // avoid a default browser page
On PHP 5.3 version, If you want to set HTTP response code. You can try this type of below trick 🙂
( ‘Temporary-Header: True’ , true , 404 );
header_remove ( ‘Temporary-Header’ );
@craig at craigfrancis dot co dot uk@ wrote the function that replaces the original. It is very usefull, but has a bug. The original http_response_code always returns the previous or current code, not the code you are setting now. Here is my fixed version. I also use $GLOBALS to store the current code, but trigger_error() instead of exit. So now, how the function will behave in the case of error lies on the error handler. Or you can change it back to exit().
if (!function_exists(‘http_response_code’)) <
function http_response_code($code = NULL) <
$prev_code = (isset($GLOBALS[‘http_response_code’]) ? $GLOBALS[‘http_response_code’] : 200);
if ($code === NULL) <
return $prev_code;
>
switch ($code) <
case 100: $text = ‘Continue’; break;
case 101: $text = ‘Switching Protocols’; break;
case 200: $text = ‘OK’; break;
case 201: $text = ‘Created’; break;
case 202: $text = ‘Accepted’; break;
case 203: $text = ‘Non-Authoritative Information’; break;
case 204: $text = ‘No Content’; break;
case 205: $text = ‘Reset Content’; break;
case 206: $text = ‘Partial Content’; break;
case 300: $text = ‘Multiple Choices’; break;
case 301: $text = ‘Moved Permanently’; break;
case 302: $text = ‘Moved Temporarily’; break;
case 303: $text = ‘See Other’; break;
case 304: $text = ‘Not Modified’; break;
case 305: $text = ‘Use Proxy’; break;
case 400: $text = ‘Bad Request’; break;
case 401: $text = ‘Unauthorized’; break;
case 402: $text = ‘Payment Required’; break;
case 403: $text = ‘Forbidden’; break;
case 404: $text = ‘Not Found’; break;
case 405: $text = ‘Method Not Allowed’; break;
case 406: $text = ‘Not Acceptable’; break;
case 407: $text = ‘Proxy Authentication Required’; break;
case 408: $text = ‘Request Time-out’; break;
case 409: $text = ‘Conflict’; break;
case 410: $text = ‘Gone’; break;
case 411: $text = ‘Length Required’; break;
case 412: $text = ‘Precondition Failed’; break;
case 413: $text = ‘Request Entity Too Large’; break;
case 414: $text = ‘Request-URI Too Large’; break;
case 415: $text = ‘Unsupported Media Type’; break;
case 500: $text = ‘Internal Server Error’; break;
case 501: $text = ‘Not Implemented’; break;
case 502: $text = ‘Bad Gateway’; break;
case 503: $text = ‘Service Unavailable’; break;
case 504: $text = ‘Gateway Time-out’; break;
case 505: $text = ‘HTTP Version not supported’; break;
default:
trigger_error(‘Unknown http status code ‘ . $code, E_USER_ERROR); // exit(‘Unknown http status code «‘ . htmlentities($code) . ‘»‘);
return $prev_code;
>
$protocol = (isset($_SERVER[‘SERVER_PROTOCOL’]) ? $_SERVER[‘SERVER_PROTOCOL’] : ‘HTTP/1.0’);
header($protocol . ‘ ‘ . $code . ‘ ‘ . $text);
$GLOBALS[‘http_response_code’] = $code;
// original function always returns the previous or current code
return $prev_code;
>
>
Источник
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 '<h1>Something went wrong!</h1>'; 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.
This is not the case.
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);
Far more concise!
(PHP 5 >= 5.4.0, PHP 7, PHP
http_response_code — Get or Set the HTTP response code
Description
http_response_code(int $response_code
= 0): int|bool
Parameters
-
response_code
-
The optional
response_code
will set the response code.
Return Values
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).
Examples
Example #1 Using http_response_code() in a web server environment
<?php// Get the current response code and set a new one
var_dump(http_response_code(404));// Get the new response code
var_dump(http_response_code());
?>
The above example will output:
Example #2 Using http_response_code() in a CLI environment
<?php// Get the current default response code
var_dump(http_response_code());// Set a response code
var_dump(http_response_code(201));// Get the new response code
var_dump(http_response_code());
?>
The above example will output:
bool(false) bool(true) int(201)
See Also
- header() — Send a raw HTTP header
- headers_list() — Returns a list of response headers sent (or ready to send)
craig at craigfrancis dot co dot uk ¶
11 years ago
If your version of PHP does not include this function:
<?phpif (!function_exists('http_response_code')) {
function http_response_code($code = NULL) {
if (
$code !== NULL) {
switch (
$code) {
case 100: $text = 'Continue'; break;
case 101: $text = 'Switching Protocols'; break;
case 200: $text = 'OK'; break;
case 201: $text = 'Created'; break;
case 202: $text = 'Accepted'; break;
case 203: $text = 'Non-Authoritative Information'; break;
case 204: $text = 'No Content'; break;
case 205: $text = 'Reset Content'; break;
case 206: $text = 'Partial Content'; break;
case 300: $text = 'Multiple Choices'; break;
case 301: $text = 'Moved Permanently'; break;
case 302: $text = 'Moved Temporarily'; break;
case 303: $text = 'See Other'; break;
case 304: $text = 'Not Modified'; break;
case 305: $text = 'Use Proxy'; break;
case 400: $text = 'Bad Request'; break;
case 401: $text = 'Unauthorized'; break;
case 402: $text = 'Payment Required'; break;
case 403: $text = 'Forbidden'; break;
case 404: $text = 'Not Found'; break;
case 405: $text = 'Method Not Allowed'; break;
case 406: $text = 'Not Acceptable'; break;
case 407: $text = 'Proxy Authentication Required'; break;
case 408: $text = 'Request Time-out'; break;
case 409: $text = 'Conflict'; break;
case 410: $text = 'Gone'; break;
case 411: $text = 'Length Required'; break;
case 412: $text = 'Precondition Failed'; break;
case 413: $text = 'Request Entity Too Large'; break;
case 414: $text = 'Request-URI Too Large'; break;
case 415: $text = 'Unsupported Media Type'; break;
case 500: $text = 'Internal Server Error'; break;
case 501: $text = 'Not Implemented'; break;
case 502: $text = 'Bad Gateway'; break;
case 503: $text = 'Service Unavailable'; break;
case 504: $text = 'Gateway Time-out'; break;
case 505: $text = 'HTTP Version not supported'; break;
default:
exit('Unknown http status code "' . htmlentities($code) . '"');
break;
}$protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');header($protocol . ' ' . $code . ' ' . $text);$GLOBALS['http_response_code'] = $code;
} else {
$code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);
}
return
$code;
}
}
?>
In this example I am using $GLOBALS, but you can use whatever storage mechanism you like... I don't think there is a way to return the current status code:
https://bugs.php.net/bug.php?id=52555
For reference the error codes I got from PHP's source code:
http://lxr.php.net/opengrok/xref/PHP_5_4/sapi/cgi/cgi_main.c#354
And how the current http header is sent, with the variables it uses:
http://lxr.php.net/opengrok/xref/PHP_5_4/main/SAPI.c#856
Stefan W ¶
8 years ago
Note that you can NOT set arbitrary response codes with this function, only those that are known to PHP (or the SAPI PHP is running on).
The following codes currently work as expected (with PHP running as Apache module):
200 – 208, 226
300 – 305, 307, 308
400 – 417, 422 – 424, 426, 428 – 429, 431
500 – 508, 510 – 511
Codes 0, 100, 101, and 102 will be sent as "200 OK".
Everything else will result in "500 Internal Server Error".
If you want to send responses with a freestyle status line, you need to use the `header()` function:
<?php header("HTTP/1.0 418 I'm A Teapot"); ?>
Thomas A. P. ¶
7 years ago
When setting the response code to non-standard ones like 420, Apache outputs 500 Internal Server Error.
This happens when using header(0,0,420) and http_response_code(420).
Use header('HTTP/1.1 420 Enhance Your Calm') instead.
Note that the response code in the string IS interpreted and used in the access log and output via http_response_code().
Anonymous ¶
9 years ago
Status codes as an array:
<?php
$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"
viaujoc at videotron dot ca ¶
2 years ago
Do not mix the use of http_response_code() and manually setting the response code header because the actual HTTP status code being returned by the web server may not end up as expected. http_response_code() does not work if the response code has previously been set using the header() function. Example:
<?php
header('HTTP/1.1 401 Unauthorized');
http_response_code(403);
print(http_response_code());
?>
The raw HTTP response will be (notice the actual status code on the first line does not match the printed http_response_code in the body):
HTTP/1.1 401 Unauthorized
Date: Tue, 24 Nov 2020 13:49:08 GMT
Server: Apache
Connection: Upgrade, Keep-Alive
Keep-Alive: timeout=5, max=100
Transfer-Encoding: chunked
Content-Type: text/html; charset=UTF-8
403
I only tested it on Apache. I am not sure if this behavior is specific to Apache or common to all PHP distributions.
Anonymous ¶
8 years ago
You can also create a enum by extending the SplEnum class.
<?php/** HTTP status codes */
class HttpStatusCode extends SplEnum {
const __default = self::OK;
const
SWITCHING_PROTOCOLS = 101;
const OK = 200;
const CREATED = 201;
const ACCEPTED = 202;
const NONAUTHORITATIVE_INFORMATION = 203;
const NO_CONTENT = 204;
const RESET_CONTENT = 205;
const PARTIAL_CONTENT = 206;
const MULTIPLE_CHOICES = 300;
const MOVED_PERMANENTLY = 301;
const MOVED_TEMPORARILY = 302;
const SEE_OTHER = 303;
const NOT_MODIFIED = 304;
const USE_PROXY = 305;
const BAD_REQUEST = 400;
const UNAUTHORIZED = 401;
const PAYMENT_REQUIRED = 402;
const FORBIDDEN = 403;
const NOT_FOUND = 404;
const METHOD_NOT_ALLOWED = 405;
const NOT_ACCEPTABLE = 406;
const PROXY_AUTHENTICATION_REQUIRED = 407;
const REQUEST_TIMEOUT = 408;
const CONFLICT = 408;
const GONE = 410;
const LENGTH_REQUIRED = 411;
const PRECONDITION_FAILED = 412;
const REQUEST_ENTITY_TOO_LARGE = 413;
const REQUESTURI_TOO_LARGE = 414;
const UNSUPPORTED_MEDIA_TYPE = 415;
const REQUESTED_RANGE_NOT_SATISFIABLE = 416;
const EXPECTATION_FAILED = 417;
const IM_A_TEAPOT = 418;
const INTERNAL_SERVER_ERROR = 500;
const NOT_IMPLEMENTED = 501;
const BAD_GATEWAY = 502;
const SERVICE_UNAVAILABLE = 503;
const GATEWAY_TIMEOUT = 504;
const HTTP_VERSION_NOT_SUPPORTED = 505;
}
Rob Zazueta ¶
9 years ago
The note above from "Anonymous" is wrong. I'm running this behind the AWS Elastic Loadbalancer and trying the header(':'.$error_code...) method mentioned above is treated as invalid HTTP.
The documentation for the header() function has the right way to implement this if you're still on < php 5.4:
<?php
header("HTTP/1.0 404 Not Found");
?>
Anonymous ¶
10 years ago
If you don't have PHP 5.4 and want to change the returned status code, you can simply write:
<?php
header(':', true, $statusCode);
?>
The ':' are mandatory, or it won't work
divinity76 at gmail dot com ¶
2 years ago
if you need a response code not supported by http_response_code(), such as WebDAV / RFC4918's "HTTP 507 Insufficient Storage", try:
<?php
header($_SERVER['SERVER_PROTOCOL'] . ' 507 Insufficient Storage');
?>
result: something like
HTTP/1.1 507 Insufficient Storage
Steven ¶
7 years ago
http_response_code is basically a shorthand way of writing a http status header, with the added bonus that PHP will work out a suitable Reason Phrase to provide by matching your response code to one of the values in an enumeration it maintains within php-src/main/http_status_codes.h. Note that this means your response code must match a response code that PHP knows about. You can't create your own response codes using this method, however you can using the header method.
In summary - The differences between "http_response_code" and "header" for setting response codes:
1. Using http_response_code will cause PHP to match and apply a Reason Phrase from a list of Reason Phrases that are hard-coded into the PHP source code.
2. Because of point 1 above, if you use http_response_code you must set a code that PHP knows about. You can't set your own custom code, however you can set a custom code (and Reason Phrase) if you use the header method.
Richard F. ¶
9 years ago
At least on my side with php-fpm and nginx this method does not change the text in the response, only the code.
<?php// HTTP/1.1 404 Not Found
http_response_code(404);?>
The resulting response is HTTP/1.1 404 OK
stephen at bobs-bits dot com ¶
8 years ago
It's not mentioned explicitly, but the return value when SETTING, is the OLD status code.
e.g.
<?php
$a
= http_response_code();
$b = http_response_code(202);
$c = http_response_code();var_dump($a, $b, $c);// Result:
// int(200)
// int(200)
// int(202)
?>
Chandra Nakka ¶
5 years ago
On PHP 5.3 version, If you want to set HTTP response code. You can try this type of below trick :)
<?php
header
('Temporary-Header: True', true, 404);
header_remove('Temporary-Header');?>
yefremov {dot} sasha () gmail {dot} com ¶
8 years ago
@craig at craigfrancis dot co dot uk@ wrote the function that replaces the original. It is very usefull, but has a bug. The original http_response_code always returns the previous or current code, not the code you are setting now. Here is my fixed version. I also use $GLOBALS to store the current code, but trigger_error() instead of exit. So now, how the function will behave in the case of error lies on the error handler. Or you can change it back to exit().
if (!function_exists('http_response_code')) {
function http_response_code($code = NULL) {
$prev_code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);
if ($code === NULL) {
return $prev_code;
}
switch ($code) {
case 100: $text = 'Continue'; break;
case 101: $text = 'Switching Protocols'; break;
case 200: $text = 'OK'; break;
case 201: $text = 'Created'; break;
case 202: $text = 'Accepted'; break;
case 203: $text = 'Non-Authoritative Information'; break;
case 204: $text = 'No Content'; break;
case 205: $text = 'Reset Content'; break;
case 206: $text = 'Partial Content'; break;
case 300: $text = 'Multiple Choices'; break;
case 301: $text = 'Moved Permanently'; break;
case 302: $text = 'Moved Temporarily'; break;
case 303: $text = 'See Other'; break;
case 304: $text = 'Not Modified'; break;
case 305: $text = 'Use Proxy'; break;
case 400: $text = 'Bad Request'; break;
case 401: $text = 'Unauthorized'; break;
case 402: $text = 'Payment Required'; break;
case 403: $text = 'Forbidden'; break;
case 404: $text = 'Not Found'; break;
case 405: $text = 'Method Not Allowed'; break;
case 406: $text = 'Not Acceptable'; break;
case 407: $text = 'Proxy Authentication Required'; break;
case 408: $text = 'Request Time-out'; break;
case 409: $text = 'Conflict'; break;
case 410: $text = 'Gone'; break;
case 411: $text = 'Length Required'; break;
case 412: $text = 'Precondition Failed'; break;
case 413: $text = 'Request Entity Too Large'; break;
case 414: $text = 'Request-URI Too Large'; break;
case 415: $text = 'Unsupported Media Type'; break;
case 500: $text = 'Internal Server Error'; break;
case 501: $text = 'Not Implemented'; break;
case 502: $text = 'Bad Gateway'; break;
case 503: $text = 'Service Unavailable'; break;
case 504: $text = 'Gateway Time-out'; break;
case 505: $text = 'HTTP Version not supported'; break;
default:
trigger_error('Unknown http status code ' . $code, E_USER_ERROR); // exit('Unknown http status code "' . htmlentities($code) . '"');
return $prev_code;
}
$protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
header($protocol . ' ' . $code . ' ' . $text);
$GLOBALS['http_response_code'] = $code;
// original function always returns the previous or current code
return $prev_code;
}
}
Anonymous ¶
4 years ago
http_response_code() does not actually send HTTP headers, it only prepares the header list to be sent later on.
So you can call http_reponse_code() to set, get and reset the HTTP response code before it gets sent.
Test code:
<php
http_response_code(500); // set the code
var_dump(headers_sent()); // check if headers are sent
http_response_code(200); // avoid a default browser page
Kubo2 ¶
6 years ago
If you want to set a HTTP response code without the need of specifying a protocol version, you can actually do it without http_response_code():
<?php
header
('Status: 404', TRUE, 404);?>
zweibieren at yahoo dot com ¶
7 years ago
The limited list given by Stefan W is out of date. I have just tested 301 and 302 and both work.
divinity76 at gmail dot com ¶
6 years ago
warning, it does not check if headers are already sent (if it is, it won't *actually* change the code, but a subsequent call will imply that it did!!),
you might wanna do something like
function ehttp_response_code(int $response_code = NULL): int {
if ($response_code === NULL) {
return http_response_code();
}
if (headers_sent()) {
throw new Exception('tried to change http response code after sending headers!');
}
return http_response_code($response_code);
}
-
Home
- http headers — How to send 500 Internal Server Error error from a PHP script
71 votes
6 answers
Get the solution ↓↓↓
I need to send «500 Internal Server Error» from an PHP script under certain conditions. The script is supposed to be called by a third party app. The script contains a couple ofdie("this happend")
statements for which I need to send the500 Internal Server Error
response code instead of the usual200 OK
. The third party script will re-send the request under certain conditions which include not receiving the200 OK
response code.
Second part of the question: I need to setup my script like this:
<?php
custom_header( "500 Internal Server Error" );
if ( that_happened ) {
die( "that happened" )
}
if ( something_else_happened ) {
die( "something else happened" )
}
update_database( );
// the script can also fail on the above line
// e.g. a mysql error occurred
remove_header( "500" );
?>
I need to send200
header only after the last line has been executed.
Edit
A side question: can I send strange 500 headers such as these:
HTTP/1.1 500 No Record Found
HTTP/1.1 500 Script Generated Error (E_RECORD_NOT_FOUND)
HTTP/1.1 500 Conditions Failed on Line 23
Will such errors get logged by the webserver?
2022-08-20
Write your answer
6
votes
Answer
Solution:
header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
661
votes
Answer
Solution:
PHP 5.4 has a function called http_response_code, so if you’re using PHP 5.4 you can just do:
http_response_code(500);
I’ve written a polyfill for this function (Gist) if you’re running a version of PHP under 5.4.
To answer your follow-up question, the HTTP 1.1 RFC says:
The reason phrases listed here are only recommendations — they MAY be
replaced by local equivalents without affecting the protocol.
That means you can use whatever text you want (excluding carriage returns or line feeds) after the code itself, and it’ll work. Generally, though, there’s usually a better response code to use. For example, instead of using a 500 for no record found, you could send a 404 (not found), and for something like «conditions failed» (I’m guessing a validation error), you could send something like a 422 (unprocessable entity).
585
votes
Answer
Solution:
You may use the following function to send a status change:
function header_status($statusCode) {
static $status_codes = null;
if ($status_codes === null) {
$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',
307 => 'Temporary 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',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
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',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended'
);
}
if ($status_codes[$statusCode] !== null) {
$status_string = $statusCode . ' ' . $status_codes[$statusCode];
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
}
}
You may use it as such:
<?php
header_status(500);
if (that_happened) {
die("that happened")
}
if (something_else_happened) {
die("something else happened")
}
update_database();
header_status(200);
768
votes
Answer
Solution:
You can just put:
header("HTTP/1.0 500 Internal Server Error");
inside your conditions like:
if (that happened) {
header("HTTP/1.0 500 Internal Server Error");
}
As for the database query, you can just do that like this:
$result = mysql_query("..query string..") or header("HTTP/1.0 500 Internal Server Error");
You should remember that you have to put this code before any html tag (or output).
508
votes
Answer
Solution:
You can simplify it like this:
if ( that_happened || something_else_happened )
{
header('X-Error-Message: Incorrect username or password', true, 500);
die;
}
It will return following header:
HTTP/1.1 500 Internal Server Error
...
X-Error-Message: Incorrect username or password
...
Added: If you need to know exactly what went wrong, do something like this:
if ( that_happened )
{
header('X-Error-Message: Incorrect username', true, 500);
die('Incorrect username');
}
if ( something_else_happened )
{
header('X-Error-Message: Incorrect password', true, 500);
die('Incorrect password');
}
168
votes
Answer
Solution:
Your code should look like:
<?php
if ( that_happened ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
if ( something_else_happened ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
// Your function should return FALSE if something goes wrong
if ( !update_database() ) {
header("HTTP/1.0 500 Internal Server Error");
die();
}
// the script can also fail on the above line
// e.g. a mysql error occurred
header('HTTP/1.1 200 OK');
?>
I assume you stop execution if something goes wrong.
Share solution ↓
Additional Information:
Date the issue was resolved:
2022-08-20
Link To Source
Link To Answer
People are also looking for solutions of the problem: constant expression contains invalid operations
Didn’t find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
About the technologies asked in this question
PHP
PHP (from the English Hypertext Preprocessor — hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
MySQL
DBMS is a database management system. It is designed to change, search, add and delete information in the database. There are many DBMSs designed for similar purposes with different features. One of the most popular is MySQL.
It is a software tool designed to work with relational SQL databases. It is easy to learn even for site owners who are not professional programmers or administrators. MySQL DBMS also allows you to export and import data, which is convenient when moving large amounts of information.
https://www.mysql.com/
HTML
HTML (English «hyper text markup language» — hypertext markup language) is a special markup language that is used to create sites on the Internet.
Browsers understand html perfectly and can interpret it in an understandable way. In general, any page on the site is html-code, which the browser translates into a user-friendly form. By the way, the code of any page is available to everyone.
https://www.w3.org/html/
Welcome to programmierfrage.com
programmierfrage.com is a question and answer site for professional web developers, programming enthusiasts and website builders. Site created and operated by the community. Together with you, we create a free library of detailed answers to any question on programming, web development, website creation and website administration.
Get answers to specific questions
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Help Others Solve Their Issues
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.
- Программирование
> - php
> - Коды ответа сервера
- Как изменить код ответа сервера
- Если требуется перенаправить на другой url
- Заголовки кодировки и языка
- Модификация заголовков для управления контентом
- Как влиять на СЕО
При серьезной разработке сайта возникает необходимость выдавать корректные http заголовки php средствами.
Вы спросите — зачем? Затем, что корректность HTTP-заголовков влияет на то, как будут понимать поисковые роботы получаемую с вашего сайта информацию, что напрямую влияет на продвижение сайта, т.е. на «СЕО».
ВАЖНО ПОМНИТЬ!
мордифицировать HTTP header с помощью языка php возможно только если директива header выводится на клиента до формировании страницы, то есть до вывода любой иной инофрмации.
В противном случае назначение нового статуса HTTP заголовку / header выдает ошибку.
Как изменить код ответа сервера.
В большинстве случаев заголовки изменяются непосредственно в ваших php функциях (методах).
<?php
function checkUrl( $url )
{
if( preg_match( «/^http.*/i», $url ) == false )
header( ‘Location: http://www.ru/404.html’ );
}
…
?>
Рассмотрим несколько примеров модификации HTTP заголовков.
Страница выполнена корректно
header( ‘HTTP/1.1 200 OK’ );
Запрашиваемая страница не найдена
header( ‘HTTP/1.1 404 Not Found’ );
Доступ запрещен:
header( ‘HTTP/1.1 403 Forbidden’ );
Страница перемещена навсегда.
Используется для корректировки урлов поисковых серверов.
header( ‘HTTP/1.1 301 Moved Permanently’ );
Сервер выполнил скрипт с ошибкой
header( ‘HTTP/1.1 500 Internal Server Error’ );
Если требуется перенаправить на другой url
Перенаправление на указанный адресу
header( ‘Location: http://www.ru/’ );
Перенаправление на указанный адрес с задержкой в 5 секунд
в принципе это калька HTML тега
<meta http-equiv=»refresh» content=»5;http://www.ru/ />
header( ‘Refresh: 5; url=http://www.ru/’ );
Заголовки кодировки и языка
Содержимое страницы использует язык:
header( ‘Content-language: en’ ); // en = English
Как поменять кодировку
header(‘Content-Type: text/html; charset=utf-8’);
Модификация заголовков для управления контентом
header( ‘Content-Type: application/octet-stream’ );
header( ‘Content-Disposition: attachment; filename=»example.zip»‘ );
header( ‘Content-Transfer-Encoding: binary’ );
Установка content type
header(‘Content-Type: text/plain’); // plain text file
header(‘Content-Type: image/jpeg’); // JPG picture
header(‘Content-Type: audio/mpeg’); // Audio MPEG (MP3,…) file
header(‘Content-Type: application/x-shockwave-flash’); // Flash animation
Иные манипуляции с заголовками
как средствами php изменять header для поисковых роботов
Содержимое страницы последний раз изменялось
header( ‘Last-Modified: ‘.gmdate( ‘D, d M Y H:i:s’, ( time() — 60 ) ).’ GMT’ );
Длинна содержимого страницы
header( ‘Content-Length: 2048’ );
Отключение кеширования страницы:
header( ‘Cache-Control: no-cache, no-store, max-age=0, must-revalidate’ );
header( ‘Expires: Mon, 1 Apr 2001 01:02:03 GMT’ );
header( ‘Pragma: no-cache’ );
- Программирование
> - php
> - Коды ответа сервера
- Предыдующая статья: Делаем собственную страницу ошибки 404
2019-12-01
Здравствуйте, уважаемый посетитель!
Сегодня в рамах рассмотрения системы обработки ошибок выполним необходимые действия по выводу пользователю сообщения о возникновении внутренней ошибки сервера Internal Server Error, соответствующей статусу HTTP 500.
Это необходимо сделать, так как никто не застрахован от возникновения подобных проблем. В таких случаях, если не предпринять соответстующих мер, пользователь в своем браузере будет видеть только лишь какой-нибудь ущербный, неполноценный вариант веб-страницы. Либо вообще пустой экран или страницу в несколько строк с непонятными для него техническими терминами.
И вот для того, чтобы упорядочить работу сайта, обеспечивая пользователя при любых ситуациях необходимой информацией, мы создадим собственную страницу 500.
А затем, для обеспечения на нее перенаправления, сформируем пользовательский обработчик фатальных ошибок PHP. Который в дальнейшем поможет нам обеспечить и другие возможности создаваемого механизма, такие как сохранение логов и отправка сообщений по email.
- Создание страницы 500
- Перехват и обработка фатальных ошибок PHP
- Буферизация вывода в PHP
- Дополнение файла .htaccess
- Проверка работы сайта при внутренней ошибке сервера
- Исходные файлы сайта
В первую очередь создадим в корне сайта новый файл с соответствующим именем, например «page_500.php». И поместим в него код страницы, которая будет отображаться при возникновении ошибки 500. А выполним это аналогично тому, как мы это делали в предыдущей статье при создании страницы 404.
Правда, сделаем это с некоторым отличием, заключающимся в том, что в этот раз при ее формировании будем использовать только разметку HTML, исключая какое-либо использование PHP.
Ведь не логично применять фрагменты кода, которые в случае возникновения фатальной ошибки PHP могут повлиять на отправку страницы, предназначенную, как раз, для обработки таких нестандартных ситуаций.
Конечно, это не относится к применению функции header(), с помощью которой отправляется HTTP заголовок с кодом 500, соответствующий внутренней ошибки сервера (строка 2 в приведенном ниже коде).
kak-vyvesti-stranicu-oshibki-500_1
Рис.1 Файл «page_500.php» с HTML-кодом страницы 500
Как видно, данный вариант по структуре полностью соответствует предыдущей странице 404, но выполнен на чистом HTML. Причем все общие блоки: шапка, меню, основное содержание и футер включены непосредственно, без применения подключающих инструкций PHP.
Что касается оформления, то в данном случае этого не требуется, так HTML-код страницы мало чем отличается от предыдущей. И как следствие, все необходимые свойства уже ранее назначены и добавлены в таблицу стилей CSS.
И в этом можно убедиться, если сейчас открыть созданную страницу через адресную строку браузера, добавив к доменному имени ее адрес /page_500.php. Как и в предыдущем случае в начале сделаем это в обычном, десктопном варианте пользовательского устройства.
Рис.2 Вид созданной страницы 500
А теперь посмотрим как это будет выглядеть при малом разрешении экрана в одно колоночном исполнении.
Рис.3 Вид страницы 500 при малом разрешении экрана
Как видно, полученная страница по форме схожа с предыдущей 404. За исключением содержания, отражающего теперь информацию о возникновении внутренней ошибки сервера, соответствующей статусу 500 протокола HTTP.
Таким образом необходимая страница создана. И теперь осталось только обеспечить на нее перенаправление.
Перехват и обработка фатальных ошибок PHP
Как ранее отмечалось, внутренняя ошибка сервера наиболее часто возникает в следствии фатальных ошибок PHP. Причем такие случаи обычно сопровождаются остановкой скрипта. Отчего идентифицировать такую ошибку с помощью того же самого скрипта не получится. Так как в этом случае выполнение в нем каких-либо последующих действий не представляется возможным.
Как вариант решения этой проблемы — применение встроенной функции обратного вызова register_shutdown_function(), предназначенной для регистрации специальной пользовательской функции, не связанной с работой скрипта. И, следовательно, способной выполнить дальнейшие преобразования, несмотря на то, что сам скрипт остановлен.
И таким образом, в случае возникновения фатальной ошибки управление передается этой зарегистрированной функции, являющейся в данном случае обработчиком.
Как может выглядеть регистрация пользовательской функции и перехват в ней последней ошибки, остановившей работу скрипта, показано в следующем фрагменте PHP-кода.
-
//—-Перехват и обработка фатальных ошибок PHP—-
-
function fatal_php(){ //Пользовательская функция
-
$error = error_get_last(); //Получение информации о последней произошедшей ошибке
-
if ($error !== NULL && in_array($error[‘type’], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR))){ //Если ошибка произошла и ее тип соответствует фатальной ошибке
-
$domen = ‘http://’.$_SERVER[‘SERVER_NAME’]; //Домен сайта
-
header(«Location: $domen/page_500.php»); //Редирект на страницу 500
-
exit; //Прекращение выполнения текущего скрипта
-
}
-
}
-
register_shutdown_function(‘fatal_php’); //Регистрация пользовательской функции обработчика фатальных ошибок PHP
-
?>
Рис.4 Перехват и обработка фатальных ошибок PHP
Здесь все строки кода сопровождаются комментариями, поэтому подробно описывать каждую из них, нет смысла.
Можно лишь отметить, что регистрация пользовательской функции выполняется, как ранее было отмечено, с помощью register_shutdown_function(), расположенной в строке 11.
А сама функция обработчика с именем fatal_php() (поз.3÷10) в начале возвращает ассоциативный массив с описанием последней произошедшей ошибки (функция error_get_last() поз.4). А затем в случае, если выявленная ошибка относится к одному из четырех необходимых типов (E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR), то с помощью функции отправки HTTP-заголовка header() (поз.7) выполняется редирект по указанному аргументом «Location» адресу, соответствующему странице 500.
В случае, если фатальная ошибка PHP возникает в процессе формирования тела страницы при отправленном HTTP-заголовке, то при установках по умолчанию, в соответствии с протоколом HTTP должна возникнуть ошибка Cannot modify header information — headers already sent by (), означающая невозможность изменения заголовка после его отправки. Более подробно об этом и о том, как решить эту проблему мы посмотрим в следующем разделе статьи.
Таким образом при использовании созданной пользовательской функции, в случае, если из-за какой-то критической ошибки PHP-скрипт остановлен, обработчик ее обнаружит и выполнит необходимые действия по ее идентификации и дальнейшей обработке.
В данном случае обработка заключается всего лишь в выполнении редиректа на страницу 500. Но в дальнейшем, когда мы перейдем к сохранению логов и оправке сообщений по email, то здесь же будем использовать и другие, необходимые для этого преобразования.
И последнее, на что необходимо обратить внимание, функция обработчика должна быть расположена в самом начале кода шаблона главной страницы файла index.php. Иными словами, чтобы все остальные PHP-инструкции, используемые при формировании веб-страницы, выполнялись только после ее регистрации. В противном случае при остановке скрипта обработчик не будет вызван и, соответственно, не сможет выполнить свою задачу.
Буферизация вывода в PHP
В созданном обработчике фатальных ошибок PHP (рис.2) с помощью функции HTTP-заголовка header() (поз.7) предусматривается редирект на страницу 500.
Однако, здесь следует учесть одно обстоятельство, а именно: в случае редиректа, выполняемого в момент формирования тела веб-страницы, уже после отправки HTTP-заголовка, непременно должна последовать ошибка Cannot modify header information — headers already sent by ().
Обусловлено это следующим. По умолчанию сервер отправляет в браузер данные веб-страницы по мере их готовности, в процессе выполнения PHP-скрипта. При этом в соответствии с протоколом HTTP, сервер в ответ на запрос должен в первую очередь отправить служебные заголовки, а уж только потом код самого тела страницы. И протоколом HTTP не допускается ситуация, когда в момент передачи тела страницы производится повторная оправка HTTP-заголовка. О чем и говорит описание вышеуказанной ошибки.
В подтверждение этому можно проверить работу созданного обработчика по состоянию на данный момент, с заведомо внесенной критической ошибкой PHP.
На скриншоте показан вариант вывода страницы «Получить скидку», у которой в код PHP файла poluchit-skidku.php специально внесена синтаксическая ошибка.
Рис.5 Ошибка при изменении заголовка после его отправки
Как видно, здесь в области основного содержания, при обнаружении в ней фатальной ошибки Parse error и остановки скрипта, присутствует также и ошибка Cannot modify header information — headers already sent by (), означающая невозможность изменения заголовка в момент передачи кода данного блока веб-страницы.
А для того, чтобы решить эту проблему и иметь возможность изменять в любой момент HTTP-заголовки, применяется, так называемая буферизация вывода в PHP.
Суть ее в том, что в этом случае при выполнении PHP, сервер не оправляет страницу по мере ее готовности, а складывает полученный код в определенный буфер, параллельно формируя HTTP-заголовки, которые в обычном режиме не допускается оправлять в момент передачи тела страницы.
И только после того, как скрипт выполнит все заложенные в него операции, то всё, что в конечном итоге оказалось в буфере, разом отправляется в браузер пользователя в правильном порядке, как это определенно протоколом HTTP — сначала заголовки, а уж потом страница, сформированная скриптом.
В PHP существуют несколько функций, предназначенных для работы с буфером. Но для данной задачи мы будем использовать только две из них ob_start() — для включения буферизации вывода и ob_end_flush() — для отправки данных из буфера и отключения буферизации.
Схематично для генерируемой HTML-страницы это можно представить следующим образом.
kak-vyvesti-stranicu-oshibki-500_2
Рис.6 Буферизация вывода в PHP
А ниже показано, как в итоге будет выглядеть код шаблона главной страницы в файле index.php после дополнения его обработчиком фатальных ошибок PHP и элементами буферизации вывода PHP (светлым фоном обозначены дополнительные фрагмента кода).
kak-vyvesti-stranicu-oshibki-500_3
Рис.7 Файл index.php с обработчиком ошибок и буферизацией вывода
Следует отметить, что для оптимизации файла index.php, ранее размещенный в начале шаблона главной страницы PHP-код, предназначенный для получения данных при формировании динамической страницы, перенесен в файл start.php, который подключается соответствующей инструкцией в строке 13.
Таким образом буферизацию вывода HTML-страницы, генерированной скриптом PHP, мы выполнили. Однако, для полноценной работы сайта при обработке ошибки 500 необходимо сделать еще одно небольшое дополнение, которые мы сейчас и рассмотрим.
Дополнение файла .htaccess
Приведенные выше преобразования предназначены для выполнения редиректа на страницу 500 в случае прерывания работы скрипта при фатальных ошибках PHP.
Но для того, чтобы это происходило и в других случаях внутренней ошибки сервера, необходимо в файл .htaccess добавить директиву ErrorDocument, аналогичную той, которую мы использовали ранее при редиректе на страницу 404. Только теперь в ней должен быть указан соответствующий адрес /page_500.php.
А заодно, в целях безопасности полезно будет вообще отключить отображение системных сообщений на экране пользователя. Так как теперь возникающие по каким-либо причинам ошибки будут фиксироваться собственным механизмом обработки ошибок и нет необходимости их выводить в браузер. Тем более, что в определенных случаях такая излишняя для пользователя информация может быть использована недоброжелателями в качестве уязвимости сайта.
В итоге файл .htaccess следует дополнить следующими директивами, которые обеспечат выполнение вышеперечисленных действий.
-
ErrorDocument 500 /page_500.php
-
php_flag display_errors 0
Рис.8 Редирект 500 в файле .htaccess
Таким образом мы сделали все необходимые преобразования для вывода страницы 500. И теперь можно проверить, как это в реальности будет работать.
Проверка работы сайта при внутренней ошибке сервера
Проверку обработки внутренней ошибки сервера выполним на примере возникновения фатальной ошибки PHP, что позволит удостовериться в корректной работе, как созданного обработчики фатальных ошибок, так и процесса буферизации вывода генерируемой страницы и редиректа на страницу 500.
Для этого в код PHP временно внесем ту же самую синтаксическую ошибку, которую ранее мы делали на промежуточном этапе (рис.5). И посмотрим, как теперь будет обработана такая ситуация.
Рис.9 Вывод страницы 500 при фатальной ошибке PHP
Как видно, теперь критическая ошибка отработана должным образом, с перенаправлением на страницу ошибки 500.
При желании, можно проверить работу сайта и при других искусственно созданных фатальных ошибках. И во всех случаях результат должен быть один — отображение собственной страницы 500. Что в итоге и требовалось получить.
В следующей статье мы создадим механизм обработки не фатальных ошибок PHP, где с помощью собственного обработчика будет обеспечиваться их перехват и сохранение сообщений в соответствующем журнале.
.
Исходные файлы сайта
Исходные файлы сайта с обновлениями, которые были сделаны в данной статье, можно скачать из прилагаемых дополнительных материалов:
- Файлы каталога www
- Таблицы базы данных MySQL
Дополнительные материалы бесплатно предоставляются только зарегистрированным пользователям.
Для скачивания исходных файлов необходимо авторизоваться под своим аккаунтом через соответствующую форму.
Для тех кто не зарегистрирован, можно это сделать на вкладке Регистрация.
С уважением,
- Следующая сатья: Перехват и обработка не фатальных ошибок PHP
Если у Вас возникли вопросы, или есть какие-либо пожелания по представлению материала, либо заметили какие-нибудь ошибки, а быть может просто хотите выразить свое мнение, пожалуйста, оставьте свои комментарии. Такая обратная связь очень важна для возможности учета мнения посетителей.
Буду Вам за это очень признателен!
<?php
/*
参考自:
http://darklaunch.com/2010/09/01/http-status-codes-in-php-http-header-response-code-function
http://snipplr.com/view/68099/
*/
function HTTPStatus($num) {
$http = array(
100 => ‘HTTP/1.1 100 Continue’,
101 => ‘HTTP/1.1 101 Switching Protocols’,
200 => ‘HTTP/1.1 200 OK’,
201 => ‘HTTP/1.1 201 Created’,
202 => ‘HTTP/1.1 202 Accepted’,
203 => ‘HTTP/1.1 203 Non-Authoritative Information’,
204 => ‘HTTP/1.1 204 No Content’,
205 => ‘HTTP/1.1 205 Reset Content’,
206 => ‘HTTP/1.1 206 Partial Content’,
300 => ‘HTTP/1.1 300 Multiple Choices’,
301 => ‘HTTP/1.1 301 Moved Permanently’,
302 => ‘HTTP/1.1 302 Found’,
303 => ‘HTTP/1.1 303 See Other’,
304 => ‘HTTP/1.1 304 Not Modified’,
305 => ‘HTTP/1.1 305 Use Proxy’,
307 => ‘HTTP/1.1 307 Temporary Redirect’,
400 => ‘HTTP/1.1 400 Bad Request’,
401 => ‘HTTP/1.1 401 Unauthorized’,
402 => ‘HTTP/1.1 402 Payment Required’,
403 => ‘HTTP/1.1 403 Forbidden’,
404 => ‘HTTP/1.1 404 Not Found’,
405 => ‘HTTP/1.1 405 Method Not Allowed’,
406 => ‘HTTP/1.1 406 Not Acceptable’,
407 => ‘HTTP/1.1 407 Proxy Authentication Required’,
408 => ‘HTTP/1.1 408 Request Time-out’,
409 => ‘HTTP/1.1 409 Conflict’,
410 => ‘HTTP/1.1 410 Gone’,
411 => ‘HTTP/1.1 411 Length Required’,
412 => ‘HTTP/1.1 412 Precondition Failed’,
413 => ‘HTTP/1.1 413 Request Entity Too Large’,
414 => ‘HTTP/1.1 414 Request-URI Too Large’,
415 => ‘HTTP/1.1 415 Unsupported Media Type’,
416 => ‘HTTP/1.1 416 Requested Range Not Satisfiable’,
417 => ‘HTTP/1.1 417 Expectation Failed’,
500 => ‘HTTP/1.1 500 Internal Server Error’,
501 => ‘HTTP/1.1 501 Not Implemented’,
502 => ‘HTTP/1.1 502 Bad Gateway’,
503 => ‘HTTP/1.1 503 Service Unavailable’,
504 => ‘HTTP/1.1 504 Gateway Time-out’,
505 => ‘HTTP/1.1 505 HTTP Version Not Supported’,
);
header($http[$num]);
return
array(
‘code’ => $num,
‘error’ => $http[$num],
);
}
/////////////////////////////////////////////////////////////////////////
// HTTP HEADER STATUS CODES
header(‘HTTP/1.1 200 OK’);
header(‘HTTP/1.1 404 Not Found’);
header(‘HTTP/1.1 403 Forbidden’);
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘HTTP/1.1 304 Not Modified’);
header(‘HTTP/1.1 500 Internal Server Error’);
header(‘Location: http://www.example.org/’);
header(‘Refresh: 10; url=http://www.example.org/’);
print ‘You will be redirected in 10 seconds’;
// you can also use the HTML syntax:
// <meta http-equiv=»refresh» content=»10;http://www.example.org/ />
// override X-Powered-By value
header(‘X-Powered-By: PHP/4.4.0’);
// content language (en = English)
header(‘Content-language: en’);
// last modified (对缓存友好)
$time = time() — 60; // or filemtime($fn), etc
header(‘Last-Modified: ‘.gmdate(‘D, d M Y H:i:s’, $time).‘ GMT’);
// set content length (对缓存友好):
header(‘Content-Length: 1234’);
// Headers for an download:
header(‘Content-Type: application/octet-stream’);
header(‘Content-Disposition: attachment; filename=»example.zip»‘);
header(‘Content-Transfer-Encoding: binary’);
// load the file to send:
readfile(‘example.zip’);
// Disable caching of the current document:
header(‘Cache-Control: no-cache, no-store, max-age=0, must-revalidate’);
header(‘Expires: Mon, 26 Jul 1997 05:00:00 GMT’); // Date in the past
header(‘Pragma: no-cache’);
// set content type:
header(‘Content-Type: text/html; charset=iso-8859-1’);
header(‘Content-Type: text/html; charset=utf-8’);
header(‘Content-Type: text/plain’); // plain text file
header(‘Content-Type: image/jpeg’); // JPG picture
header(‘Content-Type: application/zip’); // ZIP file
header(‘Content-Type: application/pdf’); // PDF file
header(‘Content-Type: audio/mpeg’); // Audio MPEG (MP3,…) file
header(‘Content-Type: application/x-shockwave-flash’); // Flash animation
// show sign in box
header(‘HTTP/1.1 401 Unauthorized’);
header(‘WWW-Authenticate: Basic realm=»Top Secret»‘);
print ‘Text that will be displayed if the user hits cancel or enters wrong login data’;
You may use the following function to send a status change:
function header_status($statusCode) {
static $status_codes = null;
if ($status_codes === null) {
$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',
307 => 'Temporary 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',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
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',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended'
);
}
if ($status_codes[$statusCode] !== null) {
$status_string = $statusCode . ' ' . $status_codes[$statusCode];
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
}
}
You may use it as such:
<?php
header_status(500);
if (that_happened) {
die("that happened")
}
if (something_else_happened) {
die("something else happened")
}
update_database();
header_status(200);
- Предыдующая статья: Делаем собственную страницу ошибки 404
2019-12-01
Здравствуйте, уважаемый посетитель!
Сегодня в рамах рассмотрения системы обработки ошибок выполним необходимые действия по выводу пользователю сообщения о возникновении внутренней ошибки сервера Internal Server Error, соответствующей статусу HTTP 500.
Это необходимо сделать, так как никто не застрахован от возникновения подобных проблем. В таких случаях, если не предпринять соответстующих мер, пользователь в своем браузере будет видеть только лишь какой-нибудь ущербный, неполноценный вариант веб-страницы. Либо вообще пустой экран или страницу в несколько строк с непонятными для него техническими терминами.
И вот для того, чтобы упорядочить работу сайта, обеспечивая пользователя при любых ситуациях необходимой информацией, мы создадим собственную страницу 500.
А затем, для обеспечения на нее перенаправления, сформируем пользовательский обработчик фатальных ошибок PHP. Который в дальнейшем поможет нам обеспечить и другие возможности создаваемого механизма, такие как сохранение логов и отправка сообщений по email.
- Создание страницы 500
- Перехват и обработка фатальных ошибок PHP
- Буферизация вывода в PHP
- Дополнение файла .htaccess
- Проверка работы сайта при внутренней ошибке сервера
- Исходные файлы сайта
В первую очередь создадим в корне сайта новый файл с соответствующим именем, например «page_500.php». И поместим в него код страницы, которая будет отображаться при возникновении ошибки 500. А выполним это аналогично тому, как мы это делали в предыдущей статье при создании страницы 404.
Правда, сделаем это с некоторым отличием, заключающимся в том, что в этот раз при ее формировании будем использовать только разметку HTML, исключая какое-либо использование PHP.
Ведь не логично применять фрагменты кода, которые в случае возникновения фатальной ошибки PHP могут повлиять на отправку страницы, предназначенную, как раз, для обработки таких нестандартных ситуаций.
Конечно, это не относится к применению функции header(), с помощью которой отправляется HTTP заголовок с кодом 500, соответствующий внутренней ошибки сервера (строка 2 в приведенном ниже коде).
kak-vyvesti-stranicu-oshibki-500_1
Рис.1 Файл «page_500.php» с HTML-кодом страницы 500
Как видно, данный вариант по структуре полностью соответствует предыдущей странице 404, но выполнен на чистом HTML. Причем все общие блоки: шапка, меню, основное содержание и футер включены непосредственно, без применения подключающих инструкций PHP.
Что касается оформления, то в данном случае этого не требуется, так HTML-код страницы мало чем отличается от предыдущей. И как следствие, все необходимые свойства уже ранее назначены и добавлены в таблицу стилей CSS.
И в этом можно убедиться, если сейчас открыть созданную страницу через адресную строку браузера, добавив к доменному имени ее адрес /page_500.php. Как и в предыдущем случае в начале сделаем это в обычном, десктопном варианте пользовательского устройства.
Рис.2 Вид созданной страницы 500
А теперь посмотрим как это будет выглядеть при малом разрешении экрана в одно колоночном исполнении.
Рис.3 Вид страницы 500 при малом разрешении экрана
Как видно, полученная страница по форме схожа с предыдущей 404. За исключением содержания, отражающего теперь информацию о возникновении внутренней ошибки сервера, соответствующей статусу 500 протокола HTTP.
Таким образом необходимая страница создана. И теперь осталось только обеспечить на нее перенаправление.
Перехват и обработка фатальных ошибок PHP
Как ранее отмечалось, внутренняя ошибка сервера наиболее часто возникает в следствии фатальных ошибок PHP. Причем такие случаи обычно сопровождаются остановкой скрипта. Отчего идентифицировать такую ошибку с помощью того же самого скрипта не получится. Так как в этом случае выполнение в нем каких-либо последующих действий не представляется возможным.
Как вариант решения этой проблемы — применение встроенной функции обратного вызова register_shutdown_function(), предназначенной для регистрации специальной пользовательской функции, не связанной с работой скрипта. И, следовательно, способной выполнить дальнейшие преобразования, несмотря на то, что сам скрипт остановлен.
И таким образом, в случае возникновения фатальной ошибки управление передается этой зарегистрированной функции, являющейся в данном случае обработчиком.
Как может выглядеть регистрация пользовательской функции и перехват в ней последней ошибки, остановившей работу скрипта, показано в следующем фрагменте PHP-кода.
-
//—-Перехват и обработка фатальных ошибок PHP—-
-
function fatal_php(){ //Пользовательская функция
-
$error = error_get_last(); //Получение информации о последней произошедшей ошибке
-
if ($error !== NULL && in_array($error[‘type’], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR))){ //Если ошибка произошла и ее тип соответствует фатальной ошибке
-
$domen = ‘http://’.$_SERVER[‘SERVER_NAME’]; //Домен сайта
-
header(«Location: $domen/page_500.php»); //Редирект на страницу 500
-
exit; //Прекращение выполнения текущего скрипта
-
}
-
}
-
register_shutdown_function(‘fatal_php’); //Регистрация пользовательской функции обработчика фатальных ошибок PHP
-
?>
Рис.4 Перехват и обработка фатальных ошибок PHP
Здесь все строки кода сопровождаются комментариями, поэтому подробно описывать каждую из них, нет смысла.
Можно лишь отметить, что регистрация пользовательской функции выполняется, как ранее было отмечено, с помощью register_shutdown_function(), расположенной в строке 11.
А сама функция обработчика с именем fatal_php() (поз.3÷10) в начале возвращает ассоциативный массив с описанием последней произошедшей ошибки (функция error_get_last() поз.4). А затем в случае, если выявленная ошибка относится к одному из четырех необходимых типов (E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR), то с помощью функции отправки HTTP-заголовка header() (поз.7) выполняется редирект по указанному аргументом «Location» адресу, соответствующему странице 500.
В случае, если фатальная ошибка PHP возникает в процессе формирования тела страницы при отправленном HTTP-заголовке, то при установках по умолчанию, в соответствии с протоколом HTTP должна возникнуть ошибка Cannot modify header information — headers already sent by (), означающая невозможность изменения заголовка после его отправки. Более подробно об этом и о том, как решить эту проблему мы посмотрим в следующем разделе статьи.
Таким образом при использовании созданной пользовательской функции, в случае, если из-за какой-то критической ошибки PHP-скрипт остановлен, обработчик ее обнаружит и выполнит необходимые действия по ее идентификации и дальнейшей обработке.
В данном случае обработка заключается всего лишь в выполнении редиректа на страницу 500. Но в дальнейшем, когда мы перейдем к сохранению логов и оправке сообщений по email, то здесь же будем использовать и другие, необходимые для этого преобразования.
И последнее, на что необходимо обратить внимание, функция обработчика должна быть расположена в самом начале кода шаблона главной страницы файла index.php. Иными словами, чтобы все остальные PHP-инструкции, используемые при формировании веб-страницы, выполнялись только после ее регистрации. В противном случае при остановке скрипта обработчик не будет вызван и, соответственно, не сможет выполнить свою задачу.
Буферизация вывода в PHP
В созданном обработчике фатальных ошибок PHP (рис.2) с помощью функции HTTP-заголовка header() (поз.7) предусматривается редирект на страницу 500.
Однако, здесь следует учесть одно обстоятельство, а именно: в случае редиректа, выполняемого в момент формирования тела веб-страницы, уже после отправки HTTP-заголовка, непременно должна последовать ошибка Cannot modify header information — headers already sent by ().
Обусловлено это следующим. По умолчанию сервер отправляет в браузер данные веб-страницы по мере их готовности, в процессе выполнения PHP-скрипта. При этом в соответствии с протоколом HTTP, сервер в ответ на запрос должен в первую очередь отправить служебные заголовки, а уж только потом код самого тела страницы. И протоколом HTTP не допускается ситуация, когда в момент передачи тела страницы производится повторная оправка HTTP-заголовка. О чем и говорит описание вышеуказанной ошибки.
В подтверждение этому можно проверить работу созданного обработчика по состоянию на данный момент, с заведомо внесенной критической ошибкой PHP.
На скриншоте показан вариант вывода страницы «Получить скидку», у которой в код PHP файла poluchit-skidku.php специально внесена синтаксическая ошибка.
Рис.5 Ошибка при изменении заголовка после его отправки
Как видно, здесь в области основного содержания, при обнаружении в ней фатальной ошибки Parse error и остановки скрипта, присутствует также и ошибка Cannot modify header information — headers already sent by (), означающая невозможность изменения заголовка в момент передачи кода данного блока веб-страницы.
А для того, чтобы решить эту проблему и иметь возможность изменять в любой момент HTTP-заголовки, применяется, так называемая буферизация вывода в PHP.
Суть ее в том, что в этом случае при выполнении PHP, сервер не оправляет страницу по мере ее готовности, а складывает полученный код в определенный буфер, параллельно формируя HTTP-заголовки, которые в обычном режиме не допускается оправлять в момент передачи тела страницы.
И только после того, как скрипт выполнит все заложенные в него операции, то всё, что в конечном итоге оказалось в буфере, разом отправляется в браузер пользователя в правильном порядке, как это определенно протоколом HTTP — сначала заголовки, а уж потом страница, сформированная скриптом.
В PHP существуют несколько функций, предназначенных для работы с буфером. Но для данной задачи мы будем использовать только две из них ob_start() — для включения буферизации вывода и ob_end_flush() — для отправки данных из буфера и отключения буферизации.
Схематично для генерируемой HTML-страницы это можно представить следующим образом.
kak-vyvesti-stranicu-oshibki-500_2
Рис.6 Буферизация вывода в PHP
А ниже показано, как в итоге будет выглядеть код шаблона главной страницы в файле index.php после дополнения его обработчиком фатальных ошибок PHP и элементами буферизации вывода PHP (светлым фоном обозначены дополнительные фрагмента кода).
kak-vyvesti-stranicu-oshibki-500_3
Рис.7 Файл index.php с обработчиком ошибок и буферизацией вывода
Следует отметить, что для оптимизации файла index.php, ранее размещенный в начале шаблона главной страницы PHP-код, предназначенный для получения данных при формировании динамической страницы, перенесен в файл start.php, который подключается соответствующей инструкцией в строке 13.
Таким образом буферизацию вывода HTML-страницы, генерированной скриптом PHP, мы выполнили. Однако, для полноценной работы сайта при обработке ошибки 500 необходимо сделать еще одно небольшое дополнение, которые мы сейчас и рассмотрим.
Дополнение файла .htaccess
Приведенные выше преобразования предназначены для выполнения редиректа на страницу 500 в случае прерывания работы скрипта при фатальных ошибках PHP.
Но для того, чтобы это происходило и в других случаях внутренней ошибки сервера, необходимо в файл .htaccess добавить директиву ErrorDocument, аналогичную той, которую мы использовали ранее при редиректе на страницу 404. Только теперь в ней должен быть указан соответствующий адрес /page_500.php.
А заодно, в целях безопасности полезно будет вообще отключить отображение системных сообщений на экране пользователя. Так как теперь возникающие по каким-либо причинам ошибки будут фиксироваться собственным механизмом обработки ошибок и нет необходимости их выводить в браузер. Тем более, что в определенных случаях такая излишняя для пользователя информация может быть использована недоброжелателями в качестве уязвимости сайта.
В итоге файл .htaccess следует дополнить следующими директивами, которые обеспечат выполнение вышеперечисленных действий.
-
ErrorDocument 500 /page_500.php
-
php_flag display_errors 0
Рис.8 Редирект 500 в файле .htaccess
Таким образом мы сделали все необходимые преобразования для вывода страницы 500. И теперь можно проверить, как это в реальности будет работать.
Проверка работы сайта при внутренней ошибке сервера
Проверку обработки внутренней ошибки сервера выполним на примере возникновения фатальной ошибки PHP, что позволит удостовериться в корректной работе, как созданного обработчики фатальных ошибок, так и процесса буферизации вывода генерируемой страницы и редиректа на страницу 500.
Для этого в код PHP временно внесем ту же самую синтаксическую ошибку, которую ранее мы делали на промежуточном этапе (рис.5). И посмотрим, как теперь будет обработана такая ситуация.
Рис.9 Вывод страницы 500 при фатальной ошибке PHP
Как видно, теперь критическая ошибка отработана должным образом, с перенаправлением на страницу ошибки 500.
При желании, можно проверить работу сайта и при других искусственно созданных фатальных ошибках. И во всех случаях результат должен быть один — отображение собственной страницы 500. Что в итоге и требовалось получить.
В следующей статье мы создадим механизм обработки не фатальных ошибок PHP, где с помощью собственного обработчика будет обеспечиваться их перехват и сохранение сообщений в соответствующем журнале.
.
Исходные файлы сайта
Исходные файлы сайта с обновлениями, которые были сделаны в данной статье, можно скачать из прилагаемых дополнительных материалов:
- Файлы каталога www
- Таблицы базы данных MySQL
Дополнительные материалы бесплатно предоставляются только зарегистрированным пользователям.
Для скачивания исходных файлов необходимо авторизоваться под своим аккаунтом через соответствующую форму.
Для тех кто не зарегистрирован, можно это сделать на вкладке Регистрация.
С уважением,
- Следующая сатья: Перехват и обработка не фатальных ошибок PHP
Если у Вас возникли вопросы, или есть какие-либо пожелания по представлению материала, либо заметили какие-нибудь ошибки, а быть может просто хотите выразить свое мнение, пожалуйста, оставьте свои комментарии. Такая обратная связь очень важна для возможности учета мнения посетителей.
Буду Вам за это очень признателен!
В статье мы расскажем, как исправить ошибку (код состояния) 500 со стороны пользователя и администратора сайта, а также подробно разберём, что такое ошибка запроса 500.
Что такое внутренняя ошибка сервера 500
Код ошибки 5хх говорит о том, что браузер отправил запрос корректно, но сервер не смог его обработать. Что значит ошибка 500? Это проблема сервера, причину которой он не может распознать.
Сообщение об ошибке сопровождается описанием. Самые популярные варианты:
- Внутренняя ошибка сервера 500,
- Ошибка 500 Internal Server Error,
- Временная ошибка (500),
- Внутренняя ошибка сервера,
- 500 ошибка сервера,
- Внутренняя ошибка HTTP 500,
- Произошла непредвиденная ошибка,
- Ошибка 500,
- HTTP status 500 internal server error (перевод ― HTTP статус 500 внутренняя ошибка сервера).
Дизайн и описание ошибки 500 может быть любым, так как каждый владелец сайта может создать свою версию страницы. Например, так выглядит страница с ошибкой на REG.RU:
Как ошибка 500 влияет на SEO-продвижение
Для продвижения сайта в поисковых системах используются поисковые роботы. Они сканируют страницы сайта, проверяя их доступность. Если страница работает корректно, роботы анализируют её содержимое. После этого формируются поисковые запросы, по которым можно найти ресурс в поиске.
Когда поисковый робот сканирует страницу с ошибкой 500, он не изменяет её статус в течение суток. В течение этого времени администратор может исправить ошибку. Если робот перейдёт на страницу и снова столкнётся с ошибкой, он исключит эту страницу из поисковой выдачи.
Проверить, осталась ли страница на прежних позициях, можно с помощью Google Search Console. Если робот исключил страницу из поисковой выдачи, её можно добавить снова.
Код ошибки 500: причины
Если сервер вернул ошибку 500, это могло случиться из-за настроек на web-хостинге или проблем с кодом сайта. Самые распространённые причины:
- ошибки в файле .htaccess,
- неподходящая версия PHP,
- некорректные права на файлы и каталоги,
- большое количество запущенных процессов,
- большие скрипты,
- несовместимые или устаревшие плагины.
Решить проблему с сервером можно только на стороне владельца веб-ресурса. Однако пользователь тоже может выполнить несколько действий, чтобы продолжить работу на сайте.
Что делать, если вы пользователь
Если на определённом ресурсе часто возникает ошибка 500, вы можете связаться с владельцем сайта по инструкции.
Перезагрузите страницу
Удаленный сервер возвращает ошибку не только из-за серьёзных проблем на сервере. Иногда 500 ошибка сервера может быть вызвана небольшими перегрузками сайта.
Чтобы устранить ошибку, перезагрузите страницу с помощью сочетания клавиш:
- на ПК — F5,
- на ноутбуке — Fn + F5,
- на устройствах от Apple — Cmd + R.
Обратите внимание! Если вы приобретаете товары в интернет-магазине и при оформлении заказа появляется 500 Internal Server Error (перевод — внутренняя ошибка сервера), при перезагрузке страницы может создаться несколько заказов. Поэтому сначала проверьте, оформился ли ваш предыдущий заказ. Если нет, попробуйте оформить заказ заново.
Очистите кэш и cookies браузера
Кэш и cookies сохраняют данные посещаемых сайтов и данные аутентификаций, чтобы в будущем загружать веб-ресурсы быстрее. Если на ресурсе уже был статус ошибки 500, при повторном входе на сайт может загружаться старая версия страницы с ошибкой из кэша, хотя на самом деле страница уже работает. Очистить кэш и куки браузера вам поможет инструкция.
Если ни одно из этих действий не решило проблему, значит, некорректно работает сам сервер сайта. Вернитесь на страницу позже, как только владелец решит проблему.
Что делать, если вы владелец сайта
В большинстве случаев устранить проблему может только владелец сайта. Как правило, ошибка связана с проблемами в коде. Реже проблемы могут быть на физическом сервере хостинг-провайдера.
Ниже рассмотрим самые популярные причины и способы решения.
Ошибки в файле .htaccess
Неверные правила в файле .htaccess — частая причина возникновения ошибки. Чтобы это проверить, найдите .htaccess в файлах сайта и переименуйте его (например, в test). Так директивы, прописанные в файле, не повлияют на работу сервера. Если сайт заработал, переименуйте файл обратно в .htaccess и найдите ошибку в директивах. Если вы самостоятельно вносили изменения в .htaccess, закомментируйте новые строки и проверьте доступность сайта.Также может помочь замена текущего файла .htaccess на стандартный в зависимости от CMS.
Найти директиву с ошибкой можно с помощью онлайн-тестировщика. Введите содержимое .htaccess и ссылку на сайт, начиная с https://. Затем нажмите Test:
Произошла непредвиденная ошибка
На экране появится отчёт. Если в .htaccess есть ошибки, они будут выделены красным цветом:
500 ошибка nginx
Активирована устаревшая версия PHP
Устаревшие версии PHP не получают обновления безопасности, работают медленнее и могут вызывать проблемы с плагинами и скриптами. Возможно, для работы вашего веб-ресурса нужна более новая версия PHP. Попробуйте сменить версию PHP на другую по инструкции.
Установлены некорректные права на файлы и каталоги сайта
В большинстве случаев корректными правами для каталогов являются «755», для файлов — «644». Проверьте, правильно ли они установлены, и при необходимости измените права на файлы и папки.
Запущено максимальное количество процессов
На тарифах виртуального хостинга REG.RU установлены ограничения на количество одновременно запущенных процессов. Например, на тарифах линейки «Эконом» установлено ограничение в 18 одновременно запущенных процессов, на тарифах «+Мощность» ― 48 процессов. Если лимит превышен, новый процесс не запускается и возникает системная ошибка 500.
Такое большое число одновременных процессов может складываться из CRON-заданий, частых подключений с помощью почтовых клиентов по протоколу IMAP, подключения по FTP или других процессов.
Чтобы проверить количество процессов, подключитесь по SSH. Выполните команду:
ps aux | grep [u]1234567 |wc -l
Вместо u1234567 укажите ваш логин хостинга: Как узнать логин хостинга.
Чтобы посмотреть, какие процессы запущены, введите команду:
Вместо u1234567 укажите логин услуги хостинга.
Командная строка отобразит запущенные процессы:
Код ошибки 500
Где:
- u1234567 — логин услуги хостинга,
- 40522 — PID процесса,
- S — приоритет процесса,
- /usr/libexec/sftp-server — название процесса.
Процесс можно завершить командой kill
, например:
Вместо 40522 укажите PID процесса.
Чтобы решить проблему, вы также можете:
- увеличить интервал запуска заданий CRON,
- ограничить количество IMAP-соединений в настройках почтового клиента. Подробнее в статье Ограничение IMAP-соединений,
- проанализировать запущенные процессы самостоятельно или обратившись за помощью к разработчикам сайта.
Если вам не удалось самостоятельно устранить ошибку 500, обратитесь в техподдержку.
Скрипты работают слишком медленно
На каждом виртуальном хостинге есть ограничения на время выполнения скрипта. Если за установленное время скрипт не успевает выполниться, возникает ошибка сервера 500. Для решения проблемы обратитесь к разработчику сайта и оптимизируйте скрипты. Если оптимизировать нельзя, перейдите на более мощный вид сервера.
У пользователей VPS есть возможность увеличить максимальное использование оперативной памяти на процесс, но лучше делать скрипты меньшего размера.
Ошибка 500 на сайте, созданном на WordPress
WordPress предлагает много плагинов для создания хорошего сайта. Они значительно расширяют возможности CMS. Однако они же могут нарушать работу сайта и вызывать ошибку 500. Вызвать ошибку могут как недавно установленные плагины, так и старые.
Для начала проверьте, нужно ли обновить плагины. Часто устаревшие плагины перестают работать и вызывают проблемы работы сайта. Если все плагины обновлены, но 500 Internal Server Error остаётся, отключите все плагины, чтобы убедиться, что именно они мешают работе сайта. Как только станет понятно, что виноват один из плагинов, отключайте их по очереди, пока не найдёте тот, который нарушает работу сервера.
Как отключить плагин в WordPress
- 1.
- 2.
Перейдите во вкладку «Плагины» ― «Установленные».
- 3.
Нажмите Деактивировать у плагина, который, как вам кажется, повлиял на работу сайта:
Если все ваши действия не решили проблему или вы не уверены в своих технических знаниях, обратитесь к службе технической поддержки. Сообщите время обнаружения проблемы и опишите все действия, которые вы предприняли перед обращением. Специалисты сделают детальную проверку настроек вашего сайта и при необходимости обратятся к администраторам сервера на стороне хостинг-провайдера.
Содержание:
- Что означает код ошибки 500 и почему она возникает?
- Где можно встретить ошибку 500?
- Все причины возникновения ошибки
-
Что делать при появлении ошибки?
- Подождать
- Сообщить администратору
-
Что делать администратору при появлении ошибки?
- Проверить файл htaccess
- Проверить лог ошибок
- Проверить содержимое CGI-скриптов
- Проверить плагины и компоненты
- Увеличить объем оперативной памяти сервера
Что означает код ошибки 500 и почему она возникает?
Коды состояния HTTP сообщают браузеру интернет-пользователя (клиенту), успешно ли выполнен запрос (получение доступа к сайту). К примеру, если браузер получает код состояния 200, то все прошло успешно. Это сообщение не видно пользователю — вместо него появляется запрошенный контент.
С кодами состояния 400 и 500 дело обстоит иначе. Первый означает, что ошибка связана с клиентом, а второй — с сервером.
Internal Server Error 500 — общий код состояния для ошибок со стороны сервера. По этой причине невозможно сразу определить, где именно возникла проблема: известно лишь то, что сервер сообщил о ней. Когда это происходит, сайт отображает посетителям страницу с сообщением об ошибке.
Где можно встретить ошибку 500?
Поскольку эта ошибка является частью спецификации HTTP для сайтов, она может появляться в любом браузере и на любом компьютере, в том числе на мобильных устройствах.
Ошибка 500 может отображаться различными способами, но в большинстве случаев сообщение включает код состояния 500, фразу «внутренняя ошибка сервера» или и то, и другое. Вот несколько распространенных примеров:
- 500 Internal Server Error;
- HTTP 500 — Internal Server Error;
- Temporary Error (500);
- Internal Server Error;
- HTTP 500 Internal Error;
- 500 Error;
- HTTP Error 500;
- 500. That’s an error.
Обычно эта ошибка отображается в окне браузера, как стандартная веб-страница.
Все причины возникновения ошибки
Internal Server Error 500 возникает, когда запрос обрабатывается сервером. Этот код состояния включает все незапланированные события, которые могут произойти на стороне сервера и помешать загрузке сайта. Одна из возможных причин — ошибка в конфигурации сервера.
Вот несколько типичных источников проблем.
- Доступ запрещен — разрешения основных файлов и папок заданы неправильно.
- Тайм-аут сеанса PHP — скрипт пытается получить доступ к внешнему ресурсу и сталкивается с задержкой.
- Некорректный код в htaccess — структура htaccess, файла для локальной настройки сервера Apache, может быть неправильной.
- Ошибка в синтаксисе и коде скриптов CGI и Perl — в этих скриптах могут встречаться неточности, в частности несогласованность путей.
- Лимит памяти PHP — процесс превышает пределы памяти и поэтому не может быть выполнен правильно.
Если сайт работает на WordPress или другой системе управления контентом, причиной ошибки может стать неисправное или несовместимое расширение. Плагины и темы — особенно от сторонних провайдеров — могут повлиять на весь сайт.
Если ошибка сохраняется в течение длительного времени, это может негативно повлиять на SEO сайта. К счастью, большинство из этих проблем можно исправить.
Что делать при появлении ошибки?
Если вы попытались открыть веб-страницу, но увидели Internal Server Error 500, можно сделать следующее.
Подождать
Поскольку ошибка исходит со стороны сервера, владельцы сайта, скорее всего, уже работают над ее устранением. Попробуйте подождать несколько минут или около часа, а затем перезагрузите страницу.
Также можно заглянуть на сайт downforeveryoneorjustme.com и вставить в поисковую строку URL-адрес страницы, на которой произошла внутренняя ошибка сервера.
Сервис сообщит, возникла ли проблема только у вас или же у всех пользователей.
Сообщить администратору
Еще один вариант — связаться с владельцами сайта. Если вы предполагаете, что они еще не знают об ошибке, лучше всего сообщить им — это поможет и вам, и другим пользователям.
У большинства сайтов и сервисов есть аккаунты в социальных сетях, а на некоторых даже указаны email-адреса и номера телефона.
Что делать администратору при появлении ошибки?
Если ошибка 500 появилась на вашем сайте, попробуйте следующие способы.
Проверить файл htaccess
Загляните в файл htaccess: даже небольшая синтаксическая ошибка может вызывать внутреннюю ошибку сервера. Не менее часто случается так, что этот файл неправильно отформатирован. Его нужно создавать в формате ASCII или ANSI, а не в Unicode. Следовательно, писать его следует в текстовом редакторе, например в Notepad, Notepad++ и Sublime Text, а не в Microsoft Word.
Чтобы проверить, является ли файл htaccess причиной ошибки, можно временно переименовать его и перезагрузить сайт. После этого сервер не будет обращаться к htaccess при загрузке страницы. Если сообщение об ошибке больше не появляется, значит стоит исправить этот файл или создать новый.
Проверить лог ошибок
Загляните в лог-файл, например для серверов Linux его можно найти по адресу /var/log/httpd/error_log. Попробуйте перезагрузить сайт, чтобы воспроизвести код ошибки 500, и посмотреть, как создается лог-файл. Это поможет быстро найти источник проблемы.
Проверить содержимое CGI-скриптов
Ошибки могут возникать, если разрешения для важных файлов установлены неправильно. Есть три типа прав:
- read (r) — чтение;
- write (w) — запись;
- execute (x) — выполнение.
Эти разрешения можно предоставлять трем типам пользователей:
- владельцу файла;
- группе пользователей;
- все остальным.
Права указываются либо с помощью сокращений r, w и x, либо с помощью числовых значений: 4 — для чтения, 2 — для записи и 1 — для выполнения. Они добавляются для каждого типа пользователей и идут один за другим: rwxr-xr-x (rwx — для владельца, r-x — для группы и r-x — для всех остальных) или 755.
По умолчанию должна быть установлена конфигурация 755. Если разрешения предоставляются иначе, может возникнуть ошибка. Эту настройку можно изменить с помощью команды: chmod 755 filename.
Если проблема не решится, можно также провести тестирование, предоставив все права для каждой группы: chmod 777 filename. Однако к этой настройке следует прибегать только для определения проблемы — если любой пользователь сможет переписывать файл, безопасность сайта окажется под угрозой.
Проверить плагины и компоненты
Новое ПО, надстройки и сторонние скрипты могут конфликтовать с текущей конфигурацией сервера. Чтобы выявить причину ошибки 500, попробуйте поочередно отключить или удалить программные дополнения.
И напротив, если вы недавно обновили ПО, текущие плагины и темы могут оказаться несовместимы с обновлением. Деактивация дополнений по порядку — лучший способ найти основную причину проблемы.
Увеличить объем оперативной памяти сервера
Лимит памяти определяет, какой ее объем может задействовать процесс. Если какой-либо процесс требует больше памяти, чем доступно, может возникать ошибка 500.
Чтобы это исправить, можно временно увеличить лимит памяти. Для этого добавьте в php.ini команду, подобную этой: memory_limit = 512M. Этот пример устанавливает лимит на 512 МБ.
Учитывайте, что хостинг-провайдер допускает лишь определенный лимит сеанса PHP в рамках используемого вами пакета. Если будет введено большее значение, сервер проигнорирует его. Также помните, что это лишь временное решение: как только сайт заработает, потребуется выяснить причину высокого потребления памяти. Высока вероятность, что в коде содержится ошибка.
Если ни один из этих способов не помог, стоит связаться с хостинг-провайдером. Но прежде чем сделать это, проверьте состояние серверов: при возникновении проблем многие провайдеры сообщают эту информацию на странице состояния или в социальных сетях.
В статье использовались материалы следующих источников:
Blog.hubspot.com
Ionos.com
Businessinsider.com
Lifewire.com
Подписывайтесь на наш Telegram-канал, чтобы быть в курсе последних новостей и событий!