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);
(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);
}
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!
500 Internal Server Error is one of the common PHP errors that can put a PHP developer in panic mode. This article provides information on the most common causes. Why it become common PHP errors ? because you will found this error in WordPress, Prestashop, Codeigniter, Java, ASP.NET or whatever.
500 Internal Server Error is not a client side problem. It’s up to the sysadmin of the Web server site to locate and analyse the logs which should give further information about the error. Based on Wikipedia, 500 Internal Server Error is A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.
Here are several common ways that you might see the HTTP 500 error:
- “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”
HOW TO FIX THE 500 INTERNAL SERVER ERROR
CHECK YOUR SERVER ERROR LOGS
With any error message, particularly one as broad as the 500 Internal Server Error, you will first want to check any Apache and PHP error logs for your server. These logs can provide valuable context related to any code failures or other potential causes of a site failure.
ERROR WITH AN .HTACCESS FILE
If you are using a .htaccess on your site, it may be interfering with the web page you are trying to load into your browser. Please double check the .htaccess configuration. Any syntax errors will cause a 500 Internal Server Error message to be displayed instead of your website.
To confirm whether a misconfiguration .htaccess is the cause of the 500 Internal Server error, either remove or rename the .htaccess file temporarily and then try to reload the page.
If your PHP script makes external network connections, the connections may time out. If too many connections are attempted and time out, this will cause a “500 Internal Server Error.” To prevent these time outs and errors, you’ll want to make sure that PHP scripts be coded with some timeout rules. Typically, however, catching a timeout error when connecting to a database or externally to remote resources (example: RSS feeds) are difficult. They, in effect, freeze the script from continuing to run.
Removing any external connections can increase both the performance of your website and decrease the chances of you receiving a “500 Internal Server Error.”
SYNTAX OR CODING ERRORS IN YOUR CGI/PERL SCRIPT
If it is a web page ending in .cgi or .pl that is producing the error, check your script for errors.
CGI Script Guidelines
When editing your CGI script, use a plain text editor – a program that saves the file as a ‘text file’ type. DO NOT use Wordpad that comes with Microsoft Windows because it doesn’t save files in pure ASCII text format. Use Notepad instead to edit files.
Upload your CGI scripts in ASCII mode into the cgi-bin directory.
Set the file permissions on the CGI script file and directories to be chmod 755. If you use an FTP program to transfer files, right-click on the file and select change file attributes.
Double-check that the Perl modules you require for your script is supported.
Troubleshoot as a 504 Gateway Timeout error instead.
It’s not very common, but some servers produce a 500 Internal Server Error when in reality a more appropriate message based on the cause of the problem is 504 Gateway Timeout.
Delete your browser’s cookies
Some 500 Internal Server Error issues can be corrected by deleting the cookies associated with the site you’re getting the error on. After removing the cookie(s), restart the browser and try again.
How To Fix the 500 Internal Server Error PrestaShop
There are two ways to turn on Error Reporting in PrestaShop depending on what version you have.
For PrestaShop v1.4 through v1.5.2
- Open config/config.inc.php
- On or around line 29 you will find this line
@ini_set('display_errors', 'off');
- Change that line to read
@ini_set('display_errors', 'on');
For PrestaShop v1.5.3+
- Open config/defines.inc.php
- On or around line 28 you will find this line
define('_PS_MODE_DEV_', false);
- Change that line to read
define('_PS_MODE_DEV_', true);
Once you enable error reporting through your FTP or CPanel, you can navigate back to your PrestaShop’s front or back office and reproduce the error or issue you are having. For example, if you are not able to access your website because of the 500 error, you will need to turn on error reporting and refresh the page(s) that had the error. There will be additional information that you can use to investigate the problem.
How To Fix the 500 Internal Server Error WordPress
Checking for Corrupt .htaccess File
The first thing you should do when troubleshooting the internal server error in WordPress is check for the corrupted .htaccess file. You can do so by renaming your main .htaccess file to something like .htaccess_old. To rename the .htaccess file, you will need to login to your site using the FTP. Once you are in, the .htaccess file will be located in the same directory where you will see folders like wp-content, wp-admin, and wp-includes.
Once you have renamed the .htaccess file, try loading your site to see if this solved the problem. If it did, then give yourself a pat on the back because you fixed the internal server error. Before you move on with other things, make sure that you go to Settings » Permalinks and click the save button. This will generate a new .htaccess file for you with proper rewrite rules to ensure that your post pages do not return a 404.
If checking for the corrupt .htaccess file solution did not work for you, then you need to continue reading this article.
Increasing the PHP Memory Limit
Sometimes this error can happen if you are exhausting your PHP memory limit. Use our tutorial on how to increase PHP memory limit in WordPress to fix that.
If you are seeing the internal server error only when you try to login to your WordPress admin or uploading an image in your wp-admin, then you should increase the memory limit by following these steps:
- Create a blank text file called php.ini
- Paste this code in there: memory=64MB
- Save the file
- Upload it into your /wp-admin/ folder using FTP
Several users have said that doing the above fixed the admin side problem for them.
If increasing the memory limit fix the problem for you, then you have fixed the problem temporarily. The reason why we say this is because there has to be something that is exhausting your memory limit. This could be a poorly coded plugin or even a theme function. We strongly recommend that you ask your WordPress web hosting company to look into the server logs to help you find the exact diagnostics.
If increasing the PHP memory limit did not fix the issue for you, then you are in for some hard-core trouble shooting.
How To Fix the 500 Internal Server Error Codeigniter
Check your error logs, sometimes the problem is with file permission, so make sure your file permission is 0755.
Read also:
[SOLUTIONS] 502 Bad Gateway Error on Nginx
[SOLUTIONS] 504 Gateway Timeout Nginx
Sources:
500 Internal Server Error – pcsupport.about.com
WHY AM I GETTING A 500 INTERNAL SERVER ERROR MESSAGE? – mediatemple.net
The 500 Internal Server Error Explained Solved
This article describes ways to minimize the occurrence of «500 Internal Server Error» messages.
- Problem
- Resolution
- Set correct permissions
- Check .htaccess directives
Problem
Visitors to your web site receive “500 Internal Server Error” messages when they access a page that uses PHP.
Resolution
Almost all of our servers run PHP as a CGI binary. One of the side effects of running PHP as a CGI binary is that internal server errors can occur if the permissions on files and directories are set incorrectly. Internal server errors can also occur if there are certain PHP directives defined in an .htaccess file.
If your web site is experiencing internal server errors, the first thing you should do is check the server logs. The server logs provide valuable information about which files are causing the errors, and potential causes. If you have a shared hosting account, you can view your web site’s error logs in cPanel. If you have a VPS or dedicated server, you can view your web site’s log files directly at the following paths:
- /usr/local/apache/logs/error_log
- /usr/local/apache/logs/suphp_log
Set correct permissions
If permission settings are causing internal server errors, you may see entries in the server logs similar to any of the following lines:
SoftException in Application.cpp:357: UID of script "/home/username/public_html/.htaccess" is smaller than min_uid SoftException in Application.cpp:146: Mismatch between target UID (511) and UID (510) of file "/home/username/public_html/index.php" SoftException in Application.cpp:256: File "/home/username/public_html/index.php" is writeable by others
These errors are all caused by permission issues. The first two lines indicate that the file’s owner or group is set incorrectly. For example, if the owner of a PHP file is the nobody or root account instead of your user account, visitors receive an internal server error when they try to view the page. If you have a shared hosting account, our Guru Crew can change the owners and groups for your files. If you need further assistance, please open a support ticket with our Guru Crew on the Customer Portal at https://my.a2hosting.com.
The third line indicates that file permissions for the index.php file are too permissive. For example, if your web site has a directory or file whose permissions are set to 777 (full permissions), anyone can read, write, or execute it. Additionally, visitors receive an internal server error when they try to view the page. To resolve this problem, change the permissions to 755 for directories and 644 for files. For example, to set the correct permissions for all directories and files in the public_html directory, type the following commands:
cd public_html find . -type d -exec chmod 755 {} ; find . -type f -exec chmod 644 {} ;
Do not change permissions on the public_html directory itself! Doing so may make your web site inaccessible.
Check .htaccess directives
Servers that run PHP as a CGI binary cannot use the php_flag or php_value directives in an .htaccess file. If directives in an .htaccess file are causing internal server errors, you will see entries in the server logs similar to the following line:
/home/username/public_html/.htaccess: Invalid command 'php_flag', perhaps misspelled or defined by a module not included in the server configuration
To resolve this problem, you must place any PHP directives into a custom php.ini file on your account, and remove or comment out any PHP directives in the .htaccess file. For information about how to set up a custom php.ini file, please see this article.
Недавно ко мне обратились из компании, занимающейся созданием сайтов, за консультацией. Были жалобы на нестабильную работу сайта. Нестабильность заключалась в том, что при сохранении публикации сайт вешался. Решение проблемы, когда возникает ошибка 500, я напишу далее. Я представлю как универсальные методы решения проблемы, которые помогут владельцам сайтов с любыми системами управления, так и направленные на решение проблемы пользователей WordPress.
Почему возникает ошибка 500(Internal Server Error)?
- Проблема в файле .htaccess;
- Некорректная работа с CGI скриптами;
- Нехватка памяти;
- Нехватка времени выполнения скрипта;
- Некорректная работа плагинов;
- Повреждение файлов.
Решение проблемы с файлом .htaccess:
Самой распространенной проблемой возникновения ошибки 500(Внутренняя ошибка сервера) является наличие в файле .htaccess команд, которые не поддерживаются сервером, либо просто неверный синтаксис команд.
Решение проблемы некорректной работа с CGI скриптами:
- Скрипты формируют неверные заголовки и необходимо смотреть логи, которые доступны из панели управления хостингом в разделе «Статистика»;
- Скрипты необходимо загружать на сервер по FTP в режиме ASCII, чтобы окончания строк в скриптах были в формате UNIX — n, а не в формате Windows — nr;
- Скрипты и папки должны быть доступны для записи только владельцу, то есть необходимо выставить права — 0755 (drwxr-xr-x).
Решение проблемы нехватки памяти:
Иногда проблема может возникать, если вы превышаете лимит выделенной памяти(PHP memory limit).
Если у вас возникает ошибка 500 при переходе в админку, при загрузке изображения или при публикации записи, то скорее всего вам поможет увеличение лимита памяти доступной PHP. Это можно сделать отредактировав существующий файл php.ini(посмотреть где он находится можно с помощью функции phpinfo(), строка — Loaded Configuration File), либо создав свой файл в корне сайта(для пользователей WordPress в wp-admin).
В php.ini необходимо написать / исправить строку: ;
memory = 64MB
Владельцы WordPress могут поступить более удобным для них образом — открыть файл wp-config.php, который лежит в корне сайта, и добавить туда следующую строку:
define('WP_MEMORY_LIMIT', '64M');
В действительности, решение проблемы таким образом скорее всего временное, так как какой-то процесс забивает память и в будущем это может произойти снова. Поэтому я рекомендую провести анализа логов, чтобы понять, из-за чего именно возникает ошибка 500.
Решение проблемы нехватки времени выполнения скрипта:
Так же, как в случае с памятью, у вас может возникнуть ситуация, когда скрипт просто не успел отработать за то время, которое ему для этого отводится. По умолчанию время выполнения скрипта ограничивается 30-ю секундами. Способы увеличения лимита далее.
Аналогично предыдущему методу работаем с php.ini:
max_execution_time = 60
Использование функции PHP — можно написать следующий код вначале какого-либо PHP файла, который запускается при возникновении проблемы(например в index.php):
ini_set( 'max_execution_time', 60 ); // 60 секунд
Работа с .htaccess:
php_value max_execution_time 60
Пользователи WordPress могут использовать плагин — WP Maximum Execution Time Exceeded.
Решение проблемы с помощью отключения плагинов:
Бывает так, что ошибка 500 возникает из-за того, что в самом плагине / модуле существует какая-либо ошибка, чаще логическая, которая приводит к негативным последствиям. Выявить «испорченный» плагин можно таким способом:
- Отключите все плагины;
- Включите первый плагин, который до этого работал вместе со всеми;
- Производите действия, которые ранее приводили к ошибке;
- Если ошибка не возникает, отключайте этот плагин и включайте следующий и т.д. пока не выявите «брак».
Если вы пользователь WordpPress и не можете зайти в админку, так как возникает ошибка 500, зайдите на сервер по FTP и переименуйте папку wp-content/plugins, в этом случае плагины автоматически отключатся, когда вы в следующий раз обратитесь к админке и если проблема была в каком-то из них, то вы войдете в админку. Далее надо будет обратно переименовать папку plugins и работать по вышеуказанной схеме.
Решение проблемы с повреждением файлов:
Если ни один из перечисленных способов до сих пор не помог решить проблему, попробуйте перезалить дистрибутив системы. Если речь идет о WordPress, то скачайте архив, распакуйте его и перебросьте файлы на сервер, либо залейте на сервер архив и распакуйте его там с заменой файлов. Вероятно какой-то из файлов системы мог быть поврежден.
Если после этой процедуры все заработает, то стоит задуматься о том, каким образом файл системы мог быть поврежден.
Что делать, если ничего не помогло?
Если ничего из вышеперечисленного не помогло, это значит, что вам все же придется либо самому, либо с помощью техподдержки хостинга анализировать логи и искать проблему более тщательно. Либо можно обратиться за помощью к профессионалам.
Post Views: 1 334
При разработке веб-сайтов и веб-приложений можно столкнуться с ошибкой 500 internal server error. Сначала она может испугать и ввести в заблуждение, поскольку обычно веб-сервер выдает более конкретные ошибки, в которых указана точная причина проблемы, например, превышено время ожидания, неверный запрос или файл не найден, а тут просто сказано что, обнаружена внутренняя ошибка.
Но не все так страшно и в большинстве случаев проблема вполне решаема и очень быстро. В этой статье мы разберем как исправить ошибку Internal server error в Nginx.
Дословно Internal server error означает внутренняя ошибка сервера. И вызвать её могут несколько проблем. Вот основные из них:
- Ошибки в скрипте на PHP — одна из самых частых причин;
- Превышено время выполнения PHP скрипта или лимит памяти;
- Неправильные права на файлы сайта;
- Неверная конфигурация Nginx.
А теперь рассмотрим каждую из причин более подробно и разберем варианты решения.
1. Ошибка в скрипте PHP
Мы привыкли к тому, что если в PHP скрипте есть ошибки, то сразу же видим их в браузере. Однако на производственных серверах отображение сообщений об ошибках в PHP отключено, чтобы предотвратить распространение информации о конфигурации сервера для посторонних. Nginx не может отобразить реальную причину ошибки, потому что не знает что за ошибка произошла, а поэтому выдает универсальное сообщение 500 internal server error.
Чтобы исправить эту ошибку, нужно сначала понять где именно проблема. Вы можете включить отображение ошибок в конфигурационном файле php изменив значение строки display_errors с off на on. Рассмотрим на примере Ubuntu и PHP 7.2:
vi /etc/php/7.2/php.ini
display_errors = On
Перезапустите php-fpm:
sudo systemctl restart php-fpm
Затем обновите страницу и вы увидите сообщение об ошибке, из-за которого возникла проблема. Далее его можно исправить и отключить отображение ошибок, тогда все будет работать. Ещё можно посмотреть сообщения об ошибках PHP в логе ошибок Nginx. Обычно он находится по пути /var/log/nginx/error.log, но для виртуальных доменов может настраиваться отдельно. Например, смотрим последние 100 строк в логе:
tail -n 100 -f /var/log/nginx/error.log
Теперь аналогично, исправьте ошибку и страница будет загружаться нормально, без ошибки 500.
2. Превышено время выполнения или лимит памяти
Это продолжение предыдущего пункта, так тоже относится к ошибкам PHP, но так, как проблема встречается довольно часто я решил вынести её в отдельный пункт. В файле php.ini установлены ограничения на время выполнения скрипта и количество оперативной памяти, которую он может потребить. Если скрипт потребляет больше, интерпретатор PHP его убивает и возвращает сообщение об ошибке.
Также подобная ошибка может возникать, если на сервере закончилась свободная оперативная память.
Если же отображение ошибок отключено, мы получаем error 500. Обратите внимание, что если время ожидания было ограничено в конфигурационном файле Nginx, то вы получите ошибку 504, а не HTTP ERROR 500, так что проблема именно в php.ini.
Чтобы решить проблему увеличьте значения параметров max_execution_time и memory_limit в php.ini:
sudo vi /etc/php/7.2/php.ini
max_execution_time 300
memory_limit 512M
Также проблема может быть вызвана превышением других лимитов установленных для скрипта php. Смотрите ошибки php, как описано в первом пункте. После внесения изменений в файл перезапустите php-fpm:
sudo systemctl restart php-fpm
3. Неверные права на файлы
Такая ошибка может возникать, если права на файлы, к которым обращается Nginx установлены на правильно. Сервисы Nginx и php-fpm должны быть запущены от имени одного и того же пользователя, а все файлы сайтов должны принадлежать этому же пользователю. Посмотреть от имени какого пользователя запущен Nginx можно командой:
nginx -T | grep user
Чтобы узнать от какого пользователя запущен php-fpm посмотрите содержимое конфигурационного файла используемого пула, например www.conf:
sudo vi /etc/php-fpm.d/www.conf
В моем случае это пользователь nginx. Теперь надо убедится, что файлы сайта, к которым вы пытаетесь обратиться принадлежат именно этому пользователю. Для этого используйте команду namei:
namei -l /var/www/site
Файлы сайта должны принадлежать пользователю, от имени которого запущены сервисы, а по пути к каталогу с файлами должен быть доступ на чтение для всех пользователей. Если файлы принадлежат не тому пользователю, то вы можете все очень просто исправить:
sudo chown nginx:nginx -R /var/www/site
Этой командой мы меняем владельца и группу всех файлов в папке на nginx:nginx. Добавить права на чтение для всех пользователей для каталога можно командой chmod. Например:
sudo chmod o+r /var/www/
Далее все должно работать. Также, проблемы с правами может вызывать SELinux. Настройте его правильно или отключите:
setenforce 0
Выводы
В этой статье мы разобрали что делать если на вашем сайте встретилась ошибка 500 internal server error nginx. Как видите проблема вполне решаема и в большинстве случаев вам помогут действия описанные в статье. А если не помогут, напишите свое решение в комментариях!
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
500 internal server error clearly indicates that something went wrong during the display of PHP page.
By default, web servers like IIS return only generic error messages in websites. Often, this causes the masking of real reason for IIS PHP errors such as 500 internal server error.
That’s why, we frequently get request from Windows server owners to find out the reason for PHP website errors and fix them as part of our Server Management Services.
Today, we’ll take a look on how Bobcares’ Engineers track the real reason and fix php 500 internal server error in IIS.
What causes PHP 500 internal server error in IIS
Basically, 500 Internal Server Error is IIS web server’s way of saying, “Something has gone wrong when I tried to display the page. Not sure what.”
Now, its time to see the exact reasons for the 500 errors.
1. Permissions Error
From our experience in managing servers, our Windows Experts often see PHP 500 internal server errors due to wrong permissions and ownership on website files. In Windows servers, every file and every folder has its own set of permissions. Again, some permissions are inherited from the parent folders too. And, when the PHP binary do not have enough permissions to execute the scripts, it can result in 500 internal server error.
Similarly, ownership of the files also create problems. In Windows, specific users like IIS User, IIS WP User, etc. should have access on the website folders and files. For example, the IUSR account should have modify permissions on php scripts. And, when there are permission problems, website shows PHP errors.
2. Bad PHP Settings
Yet another reason for PHP internal server error is bad PHP settings. The PHP settings are specified in the configuration file at C:PHPPHP.ini. PHP binary take the values from this file while executing scripts.
A classic example will be PHP timeout settings. When the website PHP scripts has to fetch results from external resources, PHP timeout values often cause trouble. Most system administrators set timeout values in PHP to avoid abuse of the server resources. And, if the PHP script executes for a time longer than the threshold limits, it eventually results in 500 error.
3. PHP module errors
A very few 500 errors happen when the PHP module on the server as such becomes corrupt too. As a result, it results in processing failure of PHP scripts.
Luckily, when the website reports the 500 error due to module failures, IIS often show a more specific error messages like:
500.0 Module or ISAPI error occurred.
500.21 Module not recognized.
How we fixed PHP 500 internal server error in IIS
Fixing PHP 500 internal server error in IIS need a series of steps. Let’s now see how our Dedicated Engineers fixed it for one of our customers and made PHP scripts running.
The customer reported 500 internal server error on WordPress website running in IIS.
1. Turning On Display errors
While the error correctly suggested that PHP had caused 500 error code, it did not provide application-specific information about what caused the error. Therefore, the the first step of investigation was to turn ON display errors option. For this, our Dedicated Engineers followed the steps below.
- Using Windows® Explorer, browse to C:PHP and open the Php.ini file in the PHP installation directory.
- Edit and set the display_errors = On directive.
- Save the file.
- Reset IIS using the command iisreset.exe
After turning on the errors, we reloaded the PHP and it showed a PHP parse error:
Parse error: parse error in C:inetpubusersxxxhttpdocsmysiteerror.php on line 3 >>
Often browser settings only show friendly error messages. In such cases, we recommend customer to turn it Off. For example, in Internet Explorer Go to Tools, Internet Options, Advanced tab, and then clear the Show friendly HTTP error messages check box.
Thus, it was a coding error on the PHP script. We suggested script modifications to customer and that fixed the error.
2. Running PHP script locally
Yet another way to find the exact error is to run the problem php script within the server. For this, our Support Engineers connect to the server via rdesktop and execute php script using the php.exe binary. It would show the DLL’s that are having conflicts and causing the 500 error. We fix these conflicts and make the script working again.
3. Correcting PHP settings
In some cases, we need to correct the PHP settings to get the problem solved. Recently, when a customer reported problems with his website, we had to set the php directive open_basedir correctly to solve 500 Internal Server Error.
Similarly, when PHP cgi scripts show up some warning, IIS7 still displays an HTTP 500 error message. Although the best method is to fix the PHP scripts, often changing the default error handling for FastCGI in IIS7 to “IgnoreAndReturn200” also work as a temporary fix. The exact settings will look as shown.
4. Fixing PHP binary
In some rare cases, the fix may involve complete rebuilding of PHP binary on the server. This happens mainly when the PHP program on the server becomes corrupt. However, in such cases our Dedicated Engineers always check the dependency of the package and do the reinstall. For control panel specific servers, we set the appropriate binary on the server.
[Broken PHP scripts causing big problems? Our IIS experts have the fix for you.]
Conclusion
In a nutshell, PHP 500 internal server error in IIS happens mainly due to reasons like buggy PHP scripts, wrong server settings and many more. Today, we saw the top reasons for the error and how our Support Engineers fix it for customers.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;