не хочу чтобы пользователи видели ошибки сайта, чтобы они писались в лог файл. Но если я выключаю показ ошибок пользователям — мне сервер выдает — ошибка 500.
ini_set("display_startup_errors","0");
ini_set('display_errors', 0);
А если включаю вывод пользователю ошибок — показывает ошибку.
Пробовал через .htaccess указать страницу при ошибке 500, но все-равно показывает «Страница недоступна» HTTP ERROR 500
ErrorDocument 500 500.php
ini_set("display_startup_errors","1");
ini_set('display_errors', 1);
Как сделать так, чтобы если есть ошибка, то пользователю не показывало текст ошибки, а просто пустую страницу, и не отдавало ошибку 500?
Закрались мысли, что что-то поменялось в ядре PHP 7.x, то ли у меня в системе какой-то комплексный баг.
Что-то на этапе парсинга или интерпретации скрипта происходит.. Но что?
Позже натокнулся на сайте php.net/manual/en/language.errors.php7.php на упоминание, что в PHP 7.0 поменялась методика обработки ошибок:
Ну так всё верно!
Из справки по PHP7
- Код: Выделить всё
Многие фатальные и поправимые фатальные ошибки были переделаны в исключения в PHP 7. Эти исключения наследуют класс Error, который, в свою очередь, реализует интерфейс Throwable (новый базовый интерфейс, который наследуют все исключения).
Это означает, пользовательские обработчики ошибок могут не быть вызваны, потому что вместо вызова ошибки, будет выброшено исключение (порождая новые фатальные ошибки из-за неперехваченных исключений класса Error).
- Код: Выделить всё
В PHP 7 механизм сообщения об ошибках был сильно изменен. Традиционное оповещение об ошибке в PHP 5 было заменено новым механизмом, в котором большинство ошибок вызываются с помощью исключений класса Error.
Как и обычные исключения, исключения Error вызываются до появления первого соответствующего блока catch. Если соответствующие блоки не предусмотрены, то будет вызван любой обработчик исключений, установленный с помощью set_exception_handler(). В случае отсутствия обработчика по умолчанию, исключение будет конвертировано в фатальную ошибку и будет обработано как традиционная ошибка.
Поскольку класс Error не наследуется от класса Exception, блок catch (Exception $e) { ... } для обработки неперехваченных исключений PHP 5 не может перехватить исключения Error. Для их перехвата используйте блок catch (Error $e) { ... } или установите обработчик исключений с помощью set_exception_handler().
И ещё, важно сказать
Если у вас PHP не показывает ошибки совсем — только белая страница
Это означает, что у вас скорее всего ошибка на этапе парсинга скрипта.
В таких случаях исполнение кода вообще не происходит, все директивы, что вы прописали для вывода ошибок в скрипте, тоже не будут исполнены — ведь скрипт просто не будет запущен после неудачного парсинга.
В общем, если у вас белая страница, то только php.ini или .htaccess вас спасут!
Для этого в php.ini обязательно должно быть прописано
- Код: Выделить всё
display_errors = on
Если доступа к php.ini нет, то можно в
.htaccess прописать
- Код: Выделить всё
php_flag display_errors on
php_flag display_startup_errors on
Кстати, в можно задать логирование ошибок в файл
- Код: Выделить всё
php_value error_log logs_directory/errors_php.log
директорию ‘logs_directory’, конечно заранее создать нужно.
Не используйте PHP-константы в конфигурационных файлах сервера!
Они там не парсятся и трактуются все как 0 ! Для сервера эти константы:
https://www.php.net/manual/en/errorfunc.constants.php
ничего не значат.
Вместо них нужно использовать битовые маски (тип int).
Например, (и учитывая, что в новых версиях PHP значение константы E_ALL может измениться) рекомендуется использовать даже не число 32767 – актуальное на сегодня для php7, а максимально большое число типа int для 32-х битной платформы – 2147483647
Т. е. в httpd.conf или в .htaccess это примерно так может выглядеть:
- Код: Выделить всё
php_flag log_errors on
php_flag display_errors on
php_value error_reporting 2147483647
php_value error_log /var/www/domains/example.com/php.error.log
I have a Ubuntu server running Apache2 with PHP 5. In the php.ini I set display_errors = On
and error_reporting = E_ALL | E_STRICT
, but PHP is still not displaying error messages. I’m also using Apache virtual hosts.
Also, what is the most strict error reporting PHP5.3 has to offer? I want my code to as up-to-date and future-proof as possible.
asked Jun 25, 2011 at 20:46
1
You also need to make sure you have your php.ini
file include the following set or errors will go only to the log that is set by default or specified in the virtual host’s configuration.
display_errors = On
The php.ini
file is where base settings for all PHP on your server, however these can easily be overridden and altered any place in the PHP code and effect everything following that change. A good check is to add the display_errors
directive to your php.ini
file. If you don’t see an error, but one is being logged, insert this at the top of the file causing the error:
ini_set('display_errors', 1);
error_reporting(E_ALL);
If this works then something earlier in your code is disabling error display.
Dezza
1,0944 gold badges22 silver badges25 bronze badges
answered Jun 26, 2011 at 16:16
RayRay
40.1k20 gold badges97 silver badges137 bronze badges
1
I had the same issue and finally solved it. My mistake was that I tried to change /etc/php5/cli/php.ini, but then I found another php.ini here: /etc/php5/apache2/php.ini, changed display_errors = On, restarted the web-server and it worked!
May be it would be helpful for someone absent-minded like me.
answered Feb 22, 2013 at 16:09
vk23vk23
4587 silver badges16 bronze badges
2
I had the same problem on my virtual server with Parallels Plesk Panel 10.4.4. The solution was (thanks to Zappa for the idea) setting error_reporting value to 32767 instead of E_ALL.
In Plesk:
Home > Subscriptions > (Select domain) > Customize > PHP Settings > error_reporting — Enter custom value — 32767
answered May 24, 2012 at 17:30
Bartek KosaBartek Kosa
8321 gold badge14 silver badges25 bronze badges
0
When you update the configuration in the php.ini file, you might have to restart apache. Try running apachectl restart
or apache2ctl restart
, or something like that.
Also, in you ini file, make sure you have display_errors = on
, but only in a development environment, never in a production machine.
Also, the strictest error reporting is exactly what you have cited, E_ALL | E_STRICT
. You can find more information on error levels at the php docs.
answered Jun 25, 2011 at 20:47
1
Check the error_reporting
flag, must be E_ALL
, but in some release of Plesk there are quotes ("E_ALL"
) instead of (E_ALL
)
I solved this issue deleting the quotes ("
) in php.ini
from this:
error_reporting = "E_ALL"
to this:
error_reporting = E_ALL
Wtower
18.5k11 gold badges102 silver badges80 bronze badges
answered Jul 4, 2015 at 18:10
1
Although this is old post…
i had similar situation that gave me headache.
Finally, i figured that i was including sub pages in index.php with «@include …»
«@» hides all errors even if display_errors is ON
answered May 4, 2014 at 7:07
TomekTomek
311 bronze badge
Make sure the php.ini that you’re modifying is on the /etc/php5/apache2 folder, or else it won’t have any efect…
answered Apr 28, 2013 at 20:30
JohnzJohnz
1141 silver badge4 bronze badges
Just want to add another pitfall here in case someone finds this question with a problem similar to mine.
When you are using Chrome (Or Chromium) and PHP triggers an error in PHP code which is located inside of a HTML attribute then Chrome removes the whole HTML element so you can’t see the PHP error in your browser.
Here is an example:
<p>
<a href="<?=missingFunc()?>">test</a>
</p>
When calling this code in Chrome you only get a HTML document with the starting <p>
tag. The rest is missing. No error message and no other HTML code after this <p>
. This is not a PHP issue. When you open this page in Firefox then you can see the error message (When viewing the HTML code). So this is a Chrome issue.
Don’t know if there is a workaround somewhere. When this happens to you then you have to test the page in Firefox or check the Apache error log.
answered May 14, 2013 at 14:28
kayahrkayahr
20.7k29 gold badges99 silver badges147 bronze badges
1
I had the same problem but I used ini_set('display_errors', '1');
inside the faulty script itself so it never fires on fatal / syntax errors. Finally I solved it by adding this to my .htaccess:
php_value auto_prepend_file /usr/www/{YOUR_PATH}/display_errors.php
display_errors.php:
<?php
ini_set('display_errors', 1);
error_reporting(-1);
?>
By that I was not forced to change the php.ini
, use it for specific subfolders and could easily disable it again.
answered Feb 27, 2017 at 2:08
mguttmgutt
5,8272 gold badges50 silver badges76 bronze badges
I have encountered also the problem. Finally I found the solution. I am using UBUNTU 16.04 LTS.
1) Open the /ect/php/7.0/apache2/php.ini
file (under the /etc/php
one might have different version of PHP but apache2/php.ini
will be under the version file), find ERROR HANDLING AND LOGGING
section and set the following value {display_error = On, error_reporting = E_ALL}
.
NOTE — Under the QUICK REFERENCE
section also one can find these values directives but don’t change there just change in Section I told.
2) Restart Apache server sudo systemctl restart apache2
Robert
5,6632 gold badges30 silver badges32 bronze badges
answered Apr 10, 2018 at 9:32
I know this thread is old but I just solved a similar problem with my Ubuntu server and thought I would add a note here to help others as this thread was first page in Google for the topic of PHP not displaying errors.
I tried several configuration settings for the error_reporting value in php.ini. From E_ALL | E_STRICT to E_ALL & E_NOTICE and none worked. I was not getting any syntax errors displayed in the browser (which is rather annoying on a development server). After changing the error_reporting setting to «E_ALL» it all started working. Not sure if it is an Ubuntu Oneric specific issue but after restarting Apache errors started showing in the HTML pages the server was serving. Seems the extra options confusing things and all error reporting stops. HTH somone else.
answered Nov 11, 2011 at 0:36
ZappaZappa
4551 gold badge5 silver badges14 bronze badges
1
I just experienced this same problem and it turned out that my problem was not in the php.ini files, but simply, that I was starting the apache server as a regular user. As soon as i did a «sudo /etc/init.d/apache2 restart», my errors were shown.
answered Jun 29, 2012 at 13:01
I had the same problem with Apache and PHP 5.5.
In php.ini
, I had the following lines:
error_reporting E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
display_errors Off
instead of the following:
error_reporting=E_ALL & ~E_NOTICE & ~E_DEPRECATED & ~E_STRICT
display_errors=Off
(the =
sign was missing)
Sk8erPeter
6,8899 gold badges48 silver badges67 bronze badges
answered Feb 12, 2014 at 10:23
1
Though this thread is old but still, I feel I should post a good answer from this stackoverflow answer.
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
This sure saved me after hours of trying to get things to work. I hope this helps someone.
answered Nov 9, 2017 at 10:54
mikaelovimikaelovi
1114 silver badges11 bronze badges
When running PHP on windows with ISS there are some configuration settings in ISS that need to be set to prevent generic default pages from being shown.
1) Double click on FastCGISettings, click on PHP then Edit. Set StandardErrorMode to ReturnStdErrLn500.
StandardErrorMode
2) Go the the site, double click on the Error Pages, click on the 500 status, click Edit Feature Settings, Change Error Responses to Detailed Errors, click ok
Change Error Responses to Detailed Errors
answered Feb 7, 2018 at 2:29
naw103naw103
1,8331 gold badge15 silver badges14 bronze badges
For me I solved it by deleting the file of php_errors.txt in the relative folder. Then the file is created automatically again when the code runs next time, and with the errors printed this time.
answered Oct 22, 2019 at 9:30
I also face the same issue, I have the following settings in my php.inni file
display_errors = On
error_reporting=E_ALL & ~E_DEPRECATED & ~E_STRICT
But still, PHP errors are not displaying on the webpage. I just restart my apache server and this problem was fixed.
answered Nov 27, 2019 at 12:47
habibhabib
1,44315 silver badges30 bronze badges
(PHP 5 >= 5.4.0, PHP 7, PHP
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
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);
}
In this tutorial, we are going to show you how to send a “404 Not Found” header using PHP.
This can be especially useful in cases when you need to display a 404 message if a particular database record does not exist.
By sending a 404 HTTP status code to the client, we can tell search engines and other crawlers that the resource does not exist.
To send a 404 to the client, we can use PHP’s http_response_code function like so.
//Send 404 response to client. http_response_code(404) //Include custom 404.php message include 'error/404.php'; //Kill the script. exit;
Note that this function is only available in PHP version 5.4 and after.
If you are using a PHP version that is older than 5.4, then you will need to use the header function instead.
//Use header function to send a 404 header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found", true, 404); //Include custom message. include 'errors/404.php'; //End the script exit;
In the code above, we.
- Send the response code to the client.
- We include a PHP file that contains our custom “404 Not Found” error. This file is not mandatory, so feel free to remove it if you want to.
- We then terminated the PHP script by calling the exit statement.
If you run one of the code samples above and check the response in your browser’s developer tools, then you will see something like this.
Request URL:http://localhost/test.php Request Method:GET Status Code:404 Not Found Remote Address:[::1]:80 Referrer Policy:no-referrer-when-downgrade
Note the Status Code segment of the server’s HTTP response. This is the 404 header.
When should I use this?
In most cases, your web server will automatically handle 404 errors if a resource does not exist.
However, what happens if your script is dynamic and it selects data from your database? What if you have a dynamic page such as users.php?id=234 and user 234 does not exist?
The file users.php will exist, so your web server will send back a status of “200 OK”, regardless of whether a user with the ID 234 exists or not.
In cases like this, we may need to manually send a 404 Not Found header.
Why isn’t PHP showing the same 404 message as my web server?
You might notice that your web server does not serve its default “404 Not Found” error message when you manually send the header with PHP.
The default message that Apache displays whenever a resource could not be found.
This is because, as far as the web server is concerned, the file does exist and it has already done its job.
One solution to this problem is to make sure that PHP and your web server display the exact same 404 message.
For example, with Apache, you can specify the path of a custom error message by using the ErrorDocument directive.
ErrorDocument 404 /errors/404.php
The Nginx web server also allows you to configure custom error messages.
(PHP 4, PHP 5, PHP 7, PHP
error_reporting — Sets which PHP errors are reported
Description
error_reporting(?int $error_level
= null
): int
Parameters
-
error_level
-
The new error_reporting
level. It takes on either a bitmask, or named constants. Using named
constants is strongly encouraged to ensure compatibility for future
versions. As error levels are added, the range of integers increases,
so older integer-based error levels will not always behave as expected.The available error level constants and the actual
meanings of these error levels are described in the
predefined constants.
Return Values
Returns the old error_reporting
level or the current level if no error_level
parameter is
given.
Changelog
Version | Description |
---|---|
8.0.0 |
error_level is nullable now.
|
Examples
Example #1 error_reporting() examples
<?php// Turn off all error reporting
error_reporting(0);// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);// Report all PHP errors
error_reporting(E_ALL);// Report all PHP errors
error_reporting(-1);// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);?>
Notes
Tip
Passing in the value -1
will show every possible error,
even when new levels and constants are added in future PHP versions. The
behavior is equivalent to passing E_ALL
constant.
See Also
- The display_errors directive
- The html_errors directive
- The xmlrpc_errors directive
- ini_set() — Sets the value of a configuration option
info at hephoz dot de ¶
14 years ago
If you just see a blank page instead of an error reporting and you have no server access so you can't edit php configuration files like php.ini try this:
- create a new file in which you include the faulty script:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("file_with_errors.php");
?>
- execute this file instead of the faulty script file
now errors of your faulty script should be reported.
this works fine with me. hope it solves your problem as well!
jcastromail at yahoo dot es ¶
2 years ago
Under PHP 8.0, error_reporting() does not return 0 when then the code uses a @ character.
For example
<?php
$a
=$array[20]; // error_reporting() returns 0 in php <8 and 4437 in PHP>=8?>
dave at davidhbrown dot us ¶
17 years ago
The example of E_ALL ^ E_NOTICE is a 'bit' confusing for those of us not wholly conversant with bitwise operators.
If you wish to remove notices from the current level, whatever that unknown level might be, use & ~ instead:
<?php
//....
$errorlevel=error_reporting();
error_reporting($errorlevel & ~E_NOTICE);
//...code that generates notices
error_reporting($errorlevel);
//...
?>
^ is the xor (bit flipping) operator and would actually turn notices *on* if they were previously off (in the error level on its left). It works in the example because E_ALL is guaranteed to have the bit for E_NOTICE set, so when ^ flips that bit, it is in fact turned off. & ~ (and not) will always turn off the bits specified by the right-hand parameter, whether or not they were on or off.
Fernando Piancastelli ¶
18 years ago
The error_reporting() function won't be effective if your display_errors directive in php.ini is set to "Off", regardless of level reporting you set. I had to set
display_errors = On
error_reporting = ~E_ALL
to keep no error reporting as default, but be able to change error reporting level in my scripts.
I'm using PHP 4.3.9 and Apache 2.0.
ecervetti at orupaca dot fr ¶
14 years ago
It could save two minutes to someone:
E_ALL & ~E_NOTICE integer value is 6135
huhiko334 at yandex dot ru ¶
4 years ago
If you get a weird mysql warnings like "Warning: mysql_query() : Your query requires a full tablescan...", don't look for error_reporting settings - it's set in php.ini.
You can turn it off with
ini_set("mysql.trace_mode","Off");
in your script
http://tinymy.link/mctct
kevinson112 at yahoo dot com ¶
5 years ago
I had the problem that if there was an error, php would just give me a blank page. Any error at all forced a blank page instead of any output whatsoever, even though I made sure that I had error_reporting set to E_ALL, display_errors turned on, etc etc. But simply running the file in a different directory allowed it to show errors!
Turns out that the error_log file in the one directory was full (2.0 Gb). I erased the file and now errors are displayed normally. It might also help to turn error logging off.
https://techysupport.co/norton-tech-support/
luisdev ¶
5 years ago
This article refers to these two reporting levels:
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
// Report all PHP errors
error_reporting(-1);
What is the difference between those two levels?
Please update this article with a clear explanation of the difference and the possible use cases.
qeremy ! gmail ¶
8 years ago
If you want to see all errors in your local environment, you can set your project URL like "foo.com.local" locally and put that in bootstrap file.
<?php
if (substr($_SERVER['SERVER_NAME'], -6) == '.local') {
ini_set('display_errors', 1);
ini_set('error_reporting', E_ALL);
// or error_reporting(E_ALL);
}
?>
adam at adamhahn dot com ¶
6 years ago
To expand upon the note by chris at ocproducts dot com. If you prepend @ to error_reporting(), the function will always return 0.
<?php
error_reporting(E_ALL);
var_dump(
error_reporting(), // value of E_ALL,
@error_reporting() // value is 0
);
?>
keithm at aoeex dot com ¶
12 years ago
Some E_STRICT errors seem to be thrown during the page's compilation process. This means they cannot be disabled by dynamically altering the error level at run time within that page.
The work-around for this was to rename the file and replace the original with a error_reporting() call and then a require() call.
Ex, rename index.php to index.inc.php, then re-create index.php as:
<?php
error_reporting(E_ALL & ~(E_STRICT|E_NOTICE));
require('index.inc.php');
?>
That allows you to alter the error reporting prior to the file being compiled.
I discovered this recently when I was given code from another development firm that triggered several E_STRICT errors and I wanted to disable E_STRICT on a per-page basis.
chris at ocproducts dot com ¶
6 years ago
The error_reporting() function will return 0 if error suppression is currently active somewhere in the call tree (via the @ operator).
Rash ¶
8 years ago
If you are using the PHP development server, run from the command line via `php -S servername:port`, every single error/notice/warning will be reported in the command line itself, with file name, and line number, and stack trace.
So if you want to keep a log of all the errors even after page reloads (for help in debugging, maybe), running the PHP development server can be useful.
vdephily at bluemetrix dot com ¶
18 years ago
Note that E_NOTICE will warn you about uninitialized variables, but assigning a key/value pair counts as initialization, and will not trigger any error :
<?php
error_reporting(E_ALL);$foo = $bar; //notice : $bar uninitialized$bar['foo'] = 'hello'; // no notice, although $bar itself has never been initialized (with "$bar = array()" for example)$bar = array('foobar' => 'barfoo');
$foo = $bar['foobar'] // ok$foo = $bar['nope'] // notice : no such index
?>
&IT ¶
3 years ago
error_reporting(E_ALL);
if (!ini_get('display_errors')) {
ini_set('display_errors', '1');
}
lhenry at lhenry dot com ¶
3 years ago
In php7, what was generally a notice or a deprecated is now a warning : the same level of a mysql error … unacceptable for me.
I do have dozen of old projects and I surely d'ont want to define every variable which I eventually wrote 20y ago.
So two option: let php7 degrade my expensive SSDs writing Gb/hours or implement smthing like server level monitoring ( with auto_[pre-ap]pend_file in php.ini) and turn off E_WARNING
Custom overriding the level of php errors should be super handy and flexible …
rojaro at gmail dot com ¶
12 years ago
To enable error reporting for *ALL* error messages including every error level (including E_STRICT, E_NOTICE etc.), simply use:
<?php error_reporting(-1); ?>
j dot schriver at vindiou dot com ¶
22 years ago
error_reporting() has no effect if you have defined your own error handler with set_error_handler()
[Editor's Note: This is not quite accurate.
E_ERROR, E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR and E_COMPILE_WARNING error levels will be handled as per the error_reporting settings.
All other levels of errors will be passed to the custom error handler defined by set_error_handler().
Zeev Suraski suggests that a simple way to use the defined levels of error reporting with your custom error handlers is to add the following line to the top of your error handling function:
if (!($type & error_reporting())) return;
-zak@php.net]
kc8yds at gmail dot com ¶
14 years ago
this is to show all errors for code that may be run on different versions
for php 5 it shows E_ALL^E_STRICT and for other versions just E_ALL
if anyone sees any problems with it please correct this post
<?php
ini_set('error_reporting', version_compare(PHP_VERSION,5,'>=') && version_compare(PHP_VERSION,6,'<') ?E_ALL^E_STRICT:E_ALL);
?>
fredrik at demomusic dot nu ¶
17 years ago
Remember that the error_reporting value is an integer, not a string ie "E_ALL & ~E_NOTICE".
This is very useful to remember when setting error_reporting levels in httpd.conf:
Use the table above or:
<?php
ini_set("error_reporting", E_YOUR_ERROR_LEVEL);
echo ini_get("error_reporting");
?>
To get the appropriate integer for your error-level. Then use:
php_admin_value error_reporting YOUR_INT
in httpd.conf
I want to share this rather straightforward tip as it is rather annoying for new php users trying to understand why things are not working when the error-level is set to (int) "E_ALL" = 0...
Maybe the PHP-developers should make ie error_reporting("E_ALL"); output a E_NOTICE informative message about the mistake?
Alex ¶
16 years ago
error_reporting() may give unexpected results if the @ error suppression directive is used.
<?php
@include 'config.php';
include 'foo.bar'; // non-existent file
?>
config.php
<?php
error_reporting(0);
?>
will throw an error level E_WARNING in relation to the non-existent file (depending of course on your configuration settings). If the suppressor is removed, this works as expected.
Alternatively using ini_set('display_errors', 0) in config.php will achieve the same result. This is contrary to the note above which says that the two instructions are equivalent.
teynon1 at gmail dot com ¶
11 years ago
It might be a good idea to include E_COMPILE_ERROR in error_reporting.
If you have a customer error handler that does not output warnings, you may get a white screen of death if a "require" fails.
Example:
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
function
myErrorHandler($errno, $errstr, $errfile, $errline) {
// Do something other than output message.
return true;
}$old_error_handler = set_error_handler("myErrorHandler");
require
"this file does not exist";
?>
To prevent this, simply include E_COMPILE_ERROR in the error_reporting.
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_COMPILE_ERROR);
?>
Daz Williams (The Northeast) ¶
14 years ago
Only display php errors to the developer...
<?php
if($_SERVER['REMOTE_ADDR']=="00.00.00.00")
{
ini_set('display_errors','On');
}
else
{
ini_set('display_errors','Off');
}
?>
Just replace 00.00.00.00 with your ip address.
DarkGool ¶
17 years ago
In phpinfo() error reporting level display like a bit (such as 4095)
Maybe it is a simply method to understand what a level set on your host
if you are not have access to php.ini file
<?php
$bit = ini_get('error_reporting');
while ($bit > 0) {
for($i = 0, $n = 0; $i <= $bit; $i = 1 * pow(2, $n), $n++) {
$end = $i;
}
$res[] = $end;
$bit = $bit - $end;
}
?>
In $res you will have all constants of error reporting
$res[]=int(16) // E_CORE_ERROR
$res[]=int(8) // E_NOTICE
...
misplacedme at gmail dot com ¶
13 years ago
I always code with E_ALL set.
After a couple of pages of
<?php
$username = (isset($_POST['username']) && !empty($_POST['username']))....
?>
I made this function to make things a little bit quicker. Unset values passed by reference won't trigger a notice.
<?php
function test_ref(&$var,$test_function='',$negate=false) {
$stat = true;
if(!isset($var)) $stat = false;
if (!empty($test_function) && function_exists($test_function)){
$stat = $test_function($var);
$stat = ($negate) ? $stat^1 : $stat;
}
elseif($test_function == 'empty') {
$stat = empty($var);
$stat = ($negate) ? $stat^1 : $stat;
}
elseif (!function_exists($test_function)) {
$stat = false;
trigger_error("$test_function() is not a valid function");
}
$stat = ($stat) ? true : false;
return $stat;
}
$a = '';
$b = '15';test_ref($a,'empty',true); //False
test_ref($a,'is_int'); //False
test_ref($a,'is_numeric'); //False
test_ref($b,'empty',true); //true
test_ref($b,'is_int'); //False
test_ref($b,'is_numeric'); //false
test_ref($unset,'is_numeric'); //false
test_ref($b,'is_number'); //returns false, with an error.
?>
forcemdt ¶
9 years ago
Php >5.4
Creating a Custom Error Handler
set_error_handler("customError",E_ALL);
function customError($errno, $errstr)
{
echo "<b>Error:</b> [$errno] $errstr<br>";
echo "Ending Script";
die();
}