This has never happened before. Usually it displays the error, but now it just gives me a 500 internal server error. Of course before, when it displayed the error, it was different servers. Now I’m on a new server (I have full root, so if I need to configure it somewhere in the php.ini, I can.) Or perhaps its something with Apache?
I’ve been putting up with it by just transferring the file to my other server and running it there to find the error, but that’s become too tedious. Is there a way to fix this?
asked Apr 22, 2010 at 1:45
1
Check the error_reporting, display_errors and display_startup_errors settings in your php.ini file. They should be set to E_ALL and "On" respectively (though you should not use display_errors on a production server, so disable this and use log_errors instead if/when you deploy it). You can also change these settings (except display_startup_errors) at the very beginning of your script to set them at runtime (though you may not catch all errors this way):
error_reporting(E_ALL);
ini_set('display_errors', 'On');
After that, restart server.
![]()
Davide
1,5951 gold badge14 silver badges29 bronze badges
answered Apr 22, 2010 at 1:49
awgyawgy
16.4k4 gold badges25 silver badges18 bronze badges
7
Use php -l <filename> (that’s an ‘L’) from the command line to output the syntax error that could be causing PHP to throw the status 500 error. It’ll output something like:
PHP Parse error: syntax error, unexpected '}' in <filename> on line 18
![]()
Matthew Lock
12.6k11 gold badges89 silver badges128 bronze badges
answered May 25, 2016 at 3:53
AaronAaron
5835 silver badges12 bronze badges
3
It’s worth noting that if your error is due to .htaccess, for example a missing rewrite_module, you’ll still see the 500 internal server error.
answered Aug 4, 2014 at 1:53
dtbarnedtbarne
8,0505 gold badges43 silver badges48 bronze badges
1
Be careful to check if
display_errors
or
error_reporting
is active (not a comment) somewhere else in the ini file.
My development server refused to display errors after upgrade to
Kubuntu 16.04 — I had checked php.ini numerous times … turned out that there was a diplay_errors = off; about 100 lines below my
display_errors = on;
So remember the last one counts!
answered Sep 9, 2016 at 15:17
![]()
MaxMax
2,4811 gold badge22 silver badges27 bronze badges
Try not to go
MAMP > conf > [your PHP version] > php.ini
but
MAMP > bin > php > [your PHP version] > conf > php.ini
and change it there, it worked for me…
answered Mar 20, 2017 at 20:57
![]()
Enabling error displaying from PHP code doesn’t work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don’t know which line. From the console, I use this:
/var/log/php-fpm# cat www-error.log | grep mycode.php
And I have the output:
[04-Apr-2016 06:58:27] PHP Parse error: syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458
This helps me find the line where I have the typo.
answered Apr 4, 2016 at 5:05
Hao NguyenHao Nguyen
5184 silver badges9 bronze badges
If all else fails try moving (i.e. in bash) all files and directories «away» and adding them back one by one.
I just found out that way that my .htaccess file was referencing a non-existant .htpasswd file. (#silly)
answered Mar 6, 2017 at 12:16
![]()
This has never happened before. Usually it displays the error, but now it just gives me a 500 internal server error. Of course before, when it displayed the error, it was different servers. Now I’m on a new server (I have full root, so if I need to configure it somewhere in the php.ini, I can.) Or perhaps its something with Apache?
I’ve been putting up with it by just transferring the file to my other server and running it there to find the error, but that’s become too tedious. Is there a way to fix this?
asked Apr 22, 2010 at 1:45
1
Check the error_reporting, display_errors and display_startup_errors settings in your php.ini file. They should be set to E_ALL and "On" respectively (though you should not use display_errors on a production server, so disable this and use log_errors instead if/when you deploy it). You can also change these settings (except display_startup_errors) at the very beginning of your script to set them at runtime (though you may not catch all errors this way):
error_reporting(E_ALL);
ini_set('display_errors', 'On');
After that, restart server.
![]()
Davide
1,5951 gold badge14 silver badges29 bronze badges
answered Apr 22, 2010 at 1:49
awgyawgy
16.4k4 gold badges25 silver badges18 bronze badges
7
Use php -l <filename> (that’s an ‘L’) from the command line to output the syntax error that could be causing PHP to throw the status 500 error. It’ll output something like:
PHP Parse error: syntax error, unexpected '}' in <filename> on line 18
![]()
Matthew Lock
12.6k11 gold badges89 silver badges128 bronze badges
answered May 25, 2016 at 3:53
AaronAaron
5835 silver badges12 bronze badges
3
It’s worth noting that if your error is due to .htaccess, for example a missing rewrite_module, you’ll still see the 500 internal server error.
answered Aug 4, 2014 at 1:53
dtbarnedtbarne
8,0505 gold badges43 silver badges48 bronze badges
1
Be careful to check if
display_errors
or
error_reporting
is active (not a comment) somewhere else in the ini file.
My development server refused to display errors after upgrade to
Kubuntu 16.04 — I had checked php.ini numerous times … turned out that there was a diplay_errors = off; about 100 lines below my
display_errors = on;
So remember the last one counts!
answered Sep 9, 2016 at 15:17
![]()
MaxMax
2,4811 gold badge22 silver badges27 bronze badges
Try not to go
MAMP > conf > [your PHP version] > php.ini
but
MAMP > bin > php > [your PHP version] > conf > php.ini
and change it there, it worked for me…
answered Mar 20, 2017 at 20:57
![]()
Enabling error displaying from PHP code doesn’t work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don’t know which line. From the console, I use this:
/var/log/php-fpm# cat www-error.log | grep mycode.php
And I have the output:
[04-Apr-2016 06:58:27] PHP Parse error: syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458
This helps me find the line where I have the typo.
answered Apr 4, 2016 at 5:05
Hao NguyenHao Nguyen
5184 silver badges9 bronze badges
If all else fails try moving (i.e. in bash) all files and directories «away» and adding them back one by one.
I just found out that way that my .htaccess file was referencing a non-existant .htpasswd file. (#silly)
answered Mar 6, 2017 at 12:16
![]()
This has never happened before. Usually it displays the error, but now it just gives me a 500 internal server error. Of course before, when it displayed the error, it was different servers. Now I’m on a new server (I have full root, so if I need to configure it somewhere in the php.ini, I can.) Or perhaps its something with Apache?
I’ve been putting up with it by just transferring the file to my other server and running it there to find the error, but that’s become too tedious. Is there a way to fix this?
asked Apr 22, 2010 at 1:45
1
Check the error_reporting, display_errors and display_startup_errors settings in your php.ini file. They should be set to E_ALL and "On" respectively (though you should not use display_errors on a production server, so disable this and use log_errors instead if/when you deploy it). You can also change these settings (except display_startup_errors) at the very beginning of your script to set them at runtime (though you may not catch all errors this way):
error_reporting(E_ALL);
ini_set('display_errors', 'On');
After that, restart server.
![]()
Davide
1,5951 gold badge14 silver badges29 bronze badges
answered Apr 22, 2010 at 1:49
awgyawgy
16.4k4 gold badges25 silver badges18 bronze badges
7
Use php -l <filename> (that’s an ‘L’) from the command line to output the syntax error that could be causing PHP to throw the status 500 error. It’ll output something like:
PHP Parse error: syntax error, unexpected '}' in <filename> on line 18
![]()
Matthew Lock
12.6k11 gold badges89 silver badges128 bronze badges
answered May 25, 2016 at 3:53
AaronAaron
5835 silver badges12 bronze badges
3
It’s worth noting that if your error is due to .htaccess, for example a missing rewrite_module, you’ll still see the 500 internal server error.
answered Aug 4, 2014 at 1:53
dtbarnedtbarne
8,0505 gold badges43 silver badges48 bronze badges
1
Be careful to check if
display_errors
or
error_reporting
is active (not a comment) somewhere else in the ini file.
My development server refused to display errors after upgrade to
Kubuntu 16.04 — I had checked php.ini numerous times … turned out that there was a diplay_errors = off; about 100 lines below my
display_errors = on;
So remember the last one counts!
answered Sep 9, 2016 at 15:17
![]()
MaxMax
2,4811 gold badge22 silver badges27 bronze badges
Try not to go
MAMP > conf > [your PHP version] > php.ini
but
MAMP > bin > php > [your PHP version] > conf > php.ini
and change it there, it worked for me…
answered Mar 20, 2017 at 20:57
![]()
Enabling error displaying from PHP code doesn’t work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don’t know which line. From the console, I use this:
/var/log/php-fpm# cat www-error.log | grep mycode.php
And I have the output:
[04-Apr-2016 06:58:27] PHP Parse error: syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458
This helps me find the line where I have the typo.
answered Apr 4, 2016 at 5:05
Hao NguyenHao Nguyen
5184 silver badges9 bronze badges
If all else fails try moving (i.e. in bash) all files and directories «away» and adding them back one by one.
I just found out that way that my .htaccess file was referencing a non-existant .htpasswd file. (#silly)
answered Mar 6, 2017 at 12:16
![]()
Этого никогда раньше не было. Обычно он отображает ошибку, но теперь она просто дает мне 500 внутренних ошибок сервера. Конечно, раньше, когда он отображал ошибку, это были разные серверы. Теперь я на новом сервере (у меня есть полный корень, поэтому, если мне нужно настроить его где-нибудь в php.ini, я могу.) Или, возможно, что-то с Apache?
Я использовал его, просто передав файл на другой сервер и запустив его там, чтобы найти ошибку, но это стало слишком утомительным. Есть ли способ исправить это?
Проверьте параметры error_reporting , display_errors и display_startup_errors в файле php.ini . Они должны быть установлены на E_ALL и "On" соответственно (хотя вы не должны использовать display_errors на производственном сервере, поэтому отключите это и используйте log_errors если при развертывании). Вы также можете изменить эти настройки (за исключением display_startup_errors ) в самом начале вашего скрипта, чтобы установить их во время выполнения (хотя вы не можете поймать все ошибки таким образом):
error_reporting(E_ALL); ini_set('display_errors', 'On');
После этого перезапустите сервер.
Стоит отметить, что если ваша ошибка связана с .htaccess, например отсутствующим rewrite_module, вы все равно увидите ошибку внутреннего сервера 500.
Используйте «php -l <filename>» (это «L») из командной строки, чтобы вывести синтаксическую ошибку, из-за которой PHP может выдать ошибку состояния 500. Он выведет что-то вроде:
Ошибка анализа паролей PHP: синтаксическая ошибка, неожиданное ‘}’ в <имя_файла> в строке 18
Включение отображения ошибок из кода PHP для меня не работает. В моем случае, используя NGINX и PHP-FMP, я отслеживаю файл журнала с помощью grep . Например, я знаю, что имя файла mycode.php вызывает ошибку 500, но не знает, какую строку. С консоли я использую это:
/var/log/php-fpm# cat www-error.log | grep mycode.php
И у меня есть выход:
[04-Apr-2016 06:58:27] PHP Parse error: syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458
Это помогает мне найти строку, где у меня есть опечатка.
Старайтесь не идти
MAMP > conf > [your PHP version] > php.ini
но
MAMP > bin > php > [your PHP version] > conf > php.ini
и изменил его там, это сработало для меня …
Будьте осторожны, проверьте,
display_errors
или
error_reporting
(не комментарий) в другом месте ini-файла.
Мой сервер разработки отказался отображать ошибки после обновления до Kubuntu 16.04 – я много раз проверял php.ini … оказалось, что существует diplay_errors = off; около 100 строк ниже моего
display_errors = on;
Так что помните, что последний имеет значение!
Если все остальное не работает, попробуйте переместить (т.е. в bash) все файлы и каталоги «прочь» и добавить их обратно один за другим.
Я просто узнал, что мой файл .htaccess ссылается на несуществующий файл .htpasswd. (#silly)
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
http_response_code — Получает или устанавливает код ответа HTTP
Описание
http_response_code(int $response_code = 0): int|bool
Список параметров
-
response_code -
Код ответа устанавливается с помощью опционального параметра
response_code.
Возвращаемые значения
Если response_code задан, то будет возвращён предыдущий код
статуса. Если response_code не задан, то будет возвращён
текущий код статуса. Оба этих значения будут по умолчанию иметь код состояния 200,
если они используются в окружении веб-сервера.
Если response_code не задан и используется не в окружении
веб-сервера (например, в CLI), то будет возвращено false. Если
response_code задан и используется не в окружении
веб-сервера, то будет возвращено true (но только если не был установлен предыдущий
код статуса).
Примеры
Пример #1 Использование http_response_code() в окружении веб-сервера
<?php// Берём текущий код и устанавливаем новый
var_dump(http_response_code(404));// Берём новый код
var_dump(http_response_code());
?>
Результат выполнения данного примера:
Пример #2 Использование http_response_code() в CLI
<?php// Берём текущий код по умолчанию
var_dump(http_response_code());// Устанавливаем код
var_dump(http_response_code(201));// Берём новый код
var_dump(http_response_code());
?>
Результат выполнения данного примера:
bool(false) bool(true) int(201)
Смотрите также
- header() — Отправка HTTP-заголовка
- headers_list() — Возвращает список переданных заголовков (или готовых к отправке)
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;
}
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
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
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
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.
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)
?>
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
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;
}
}
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);
}
Нет кода без ошибок. Как говорят, на ошибках учатся. Ну, а мы сегодня научимся включать и отключать вывод ошибок в PHP.
Если вы видите белый экран, вместо какого-либо ожидаемого результата, значит скорее всего в вашем коде произошла ошибка. Посмотрите, если в ответе сервера пришёл статус ошибки, например 500, но при этом на экране ничего нет, то вам нужно включить вывод ошибок.
Включить ошибки в PHP
Включение ошибок и предупреждений в php-скрипте
Для того, чтобы включить ошибки прямо в скрипте, перед выполняемым кодом напишите следующее:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
После этого обновите страницу, сообщение об ошибке должно отобразиться. Вы также можете включить ошибки и предупреждения на уровне сервера.
Включение ошибок и предупреждений в файле .htaccess
Если у вас есть доступ к редактированию файла .htaccess, то пропишите в нём следующие строки:
php_value display_errors 1 php_value display_startup_errors 1 php_value error_reporting E_ALL
После этого перезапустите Apache.
Включение ошибок и предупреждений в файле php.ini
Конечно же, можно настроить отображение ошибок в конфигурационном файле PHP. Для этого, добавить в файл php.ini следующее:
error_reporting = E_ALL display_errors = On display_startup_errors = On
После этого перезапустите PHP.
Такого никогда не было. Обычно он отображает ошибку, но теперь он просто дает мне внутреннюю ошибку сервера 500. Конечно, раньше, когда он отображал ошибку, это были разные серверы. Теперь я нахожусь на новом сервере (у меня есть полный root-доступ, поэтому, если мне нужно настроить его где-нибудь в php.ini, я могу.) Или, может быть, это что-то с Apache?
Я терпел это, просто передавая файл на другой сервер и запуская его там, чтобы найти ошибку, но это стало слишком утомительно. Есть ли способ исправить это?
7 ответы
Проверить error_reporting, display_errors и display_startup_errors настройки в вашем php.ini файл. Они должны быть установлены на E_ALL и "On" соответственно (хотя вы не должны использовать display_errors на производственном сервере, поэтому отключите это и используйте log_errors вместо этого, если / когда вы его развернете). Вы также можете изменить эти настройки (кроме display_startup_errors) в самом начале вашего скрипта, чтобы установить их во время выполнения (хотя вы можете не отловить все ошибки таким образом):
error_reporting(E_ALL);
ini_set('display_errors', 'On');
После этого перезапустите сервер.
Создан 07 янв.
Используйте «php -l «(это буква» L «) из командной строки для вывода синтаксической ошибки, которая может привести к тому, что PHP выдаст ошибку статуса 500. Он выведет что-то вроде:
Ошибка синтаксического анализа PHP: синтаксическая ошибка, неожиданный символ ‘}’ в в строке 18
ответ дан 25 мая ’16, 04:05
Стоит отметить, что если ваша ошибка связана с .htaccess, например, с отсутствующим rewrite_module, вы все равно увидите внутреннюю ошибку сервера 500.
ответ дан 04 мар ’15, в 21:03
Будьте осторожны, чтобы проверить, если
display_errors
or
error_reporting
активен (не является комментарием) где-то еще в ini-файле.
Мой сервер разработки отказывался отображать ошибки после обновления до Kubuntu 16.04 — я много раз проверял php.ini … Оказалось, что это «iplay_errors = off »; примерно на 100 строк ниже моего
display_errors = on;
Так что помните, последнее имеет значение!
Создан 09 сен.
Постарайся не уходить
MAMP > conf > [your PHP version] > php.ini
но
MAMP > bin > php > [your PHP version] > conf > php.ini
и поменять там, у меня сработало …
Создан 18 ноя.
Включение отображения ошибок из кода PHP у меня не работает. В моем случае, используя NGINX и PHP-FMP, я отслеживаю файл журнала, используя GREP. Например, я знаю имя файла мой код.php вызывает ошибку 500, но не знаю, в какой строке. С консоли я использую это:
/var/log/php-fpm# cat www-error.log | grep mycode.php
И у меня есть вывод:
[04-Apr-2016 06:58:27] PHP Parse error: syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458
Это помогает мне найти строку, в которой есть опечатка.
ответ дан 04 апр.
Если ничего не помогает, попробуйте переместить (например, в bash) все файлы и каталоги «прочь» и добавить их один за другим.
Я только что узнал, что мой файл .htaccess ссылается на несуществующий файл .htpasswd. (#глупый)
ответ дан 06 мар ’17, в 12:03
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
apache
php
or задайте свой вопрос.