Php отловить ошибку 500

PHP fatal errors come back as status code 200 to the HTTP client. How can I make it return a status code 500 (Internal server error)?

pnuts's user avatar

pnuts

58.1k11 gold badges86 silver badges138 bronze badges

asked Oct 12, 2009 at 17:25

Mike's user avatar

3

header("HTTP/1.1 500 Internal Server Error");

answered Oct 12, 2009 at 17:28

C. K. Young's user avatar

C. K. YoungC. K. Young

219k45 gold badges381 silver badges435 bronze badges

3

This is exactly the problem I had yesterday and I found solution as follows:

1) first of all, you need to catch PHP fatal errors, which is error type E_ERROR. when this error occurs, script will be stored the error and terminate execution. you can get the stored error by calling function error_get_last().

2) before script terminated, a callback function register_shutdown_function() will always be called. so you need to register a error handler by this function to do what you want, in this case, return header 500 and a customized internal error page (optional).

function my_error_handler()
{
  $last_error = error_get_last();
  if ($last_error && $last_error['type']==E_ERROR)
      {
        header("HTTP/1.1 500 Internal Server Error");
        echo '...';//html for 500 page
      }
}
register_shutdown_function('my_error_handler');

Note: if you want to catch custom error type, which start with E_USER*, you can use function set_error_handler() to register error handler and trigger error by function trigger_error, however, this error handler can not handle E_ERROR error type. see explanation on php.net about error handler

Dmitry Pashkevich's user avatar

answered Jan 13, 2012 at 14:09

fuyi's user avatar

fuyifuyi

2,5334 gold badges22 silver badges46 bronze badges

2

Standard PHP configuration does return 500 when error occurs! Just make sure that your display_errors = off. You can simulate it with:

ini_set('display_errors', 0); 
noFunction();

On production display_errors directive is off by default.

answered Apr 5, 2016 at 13:27

lukyer's user avatar

lukyerlukyer

7,4453 gold badges37 silver badges31 bronze badges

2

I have used «set_exception_handler» to handle uncaught exceptions.

function handleException($ex) {
      error_log("Uncaught exception class=" . get_class($ex) . " message=" . $ex->getMessage() . " line=" . $ex->getLine());
      ob_end_clean(); # try to purge content sent so far
      header('HTTP/1.1 500 Internal Server Error');
      echo 'Internal error';
    }

set_exception_handler('handleException');

answered Sep 23, 2010 at 10:10

Matti Haavikko's user avatar

2

Since PHP >= 5.4

http_response_code(500);
echo json_encode( [ 'success' => false , 'message' => 'Crazy thing just happened!' ]);
exit();

Please set the httpCode before echo.

answered Jun 16, 2020 at 5:09

vanduc1102's user avatar

vanduc1102vanduc1102

5,6401 gold badge45 silver badges42 bronze badges

It is not possible to handle PHP E_ERROR in any way according to the PHP documentation:
http://www.php.net/manual/en/function.set-error-handler.php

Nor is is possible to handle «E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT» according to that link.

You CAN provide a handler for the other error, warning, and notices including E_USER_ERROR, but that’s really not as useful as it sounds since this error only gets thrown intentionally by the programmer with trigger_error().

And of course you can catch any Exception (even the ones thrown by the native PHP functions).

I agree that this is a problem. Servers should NOT return 200 OK when application code crashes and burns.

answered Jan 24, 2010 at 2:41

Jonathan Hanson's user avatar

Jonathan HansonJonathan Hanson

4,6111 gold badge19 silver badges16 bronze badges

1

answered Oct 12, 2009 at 17:28

Xinus's user avatar

XinusXinus

29.4k30 gold badges118 silver badges165 bronze badges

1

You would have to catch the thrown error using try/catch and then use that catch block to send a header() with the 500 error.

try {
    ...badcode...
    throw new Exception('error');

} catch (Exception $e) {

    header("Status: 500 Server Error");
    var_dump($e->getMessage());
}

If the fatal exception is not surrounded by try {} catch blocks then you must register a global handler and use register_shutdown_function() to check for an error at script end.

answered Oct 12, 2009 at 17:30

Xeoncross's user avatar

XeoncrossXeoncross

55.3k79 gold badges260 silver badges363 bronze badges

5

Never forget to set header("HTTP/1.1 200 OK", true, 200); as the last line of any execution path:

//first things first:
header("HTTP/1.1 500 Internal Server Error", true, 500);


//Application code, includes, requires, etc. [...]


//somewhere something happens
//die();
throw new Exception("Uncaught exception!");


//last things last, only reached if code execution was not stopped by uncaught exception or some fatal error
header("HTTP/1.1 200 OK", true, 200);

In PHP 5.4 you can replace the header function above with the much better http_response_code(200) or http_response_code(500).

answered Aug 1, 2012 at 17:41

oxygen's user avatar

oxygenoxygen

5,8546 gold badges37 silver badges68 bronze badges

2

The hard thing when dealing with fatal errors (compile errors, for example a missing semicolon) is that the script won’t be executed, so it won’t help to set the status code in that script. However, when you include or require a script, the calling script will be executed, regardless of errors in the included script. With this, I come to this solution:

rock-solid-script.php:

// minimize changes to this script to keep it rock-solid
http_response_code(500); // PHP >= 5.4
require_once("script-i-want-to-guard-for-errors.php");

script-i-want-to-guard-for-errors.php:

// do all the processsing
// don't produce any output
// you might want to use output buffering

http_response_code(200); // PHP >= 5.4

// here you can produce the output

Direct your call to the rock-solid-script.php and you’re ready to go.

I would have liked it better to set the default status code to 500 in .htaccess. That seems more elegant to me but I can’t find a way to pull it off. I tried the RewriteRule R-flag, but this prevents execution of php altogether, so that’s no use.

answered Feb 22, 2013 at 17:50

Remco Nijhuis's user avatar

I know this is an old thread, but when I searched on Google, it jumps out as the first answer. I was trying to figure out how to do it these days, so I think I should post my workaround from 2018.

As you all have known, no, you cannot simply trigger Apache’s error pages from PHP. There’s no way doing it. So the best workaround I could find, after some research, is to use a PHP function to display the custom error pages, which is called from both what you specified in Apache, and the page that you want to trigger 500 Internal Server Error.

Here is my conf of Apache:

ErrorDocument 400 /error.php
ErrorDocument 401 /error.php
ErrorDocument 403 /error.php
ErrorDocument 404 /error.php
ErrorDocument 500 /error.php

As you could see, all 4xx and 500 errors are redirected to a same php file. Why I’m not using separate files for each code is another question, which has nothing to do with your question here, so let’s forget it and focus on error.php for now.

Here are some lines of error.php:

<?php
require_once("error_page.php");

$relative_path = "";
$internal_server_error = FALSE;

if (isset($_SERVER['REDIRECT_URL']) && $_SERVER['REDIRECT_URL'] != "")
{
    $relative_path = $_SERVER['REDIRECT_URL'];
    $internal_server_error = (http_response_code() >= 500);
}
else if (isset($_SERVER['REQUEST_URI']))
{
    $relative_path = $_SERVER['REQUEST_URI'];
}

ErrorPage::GenerateErrorPage($internal_server_error, $relative_path);
?>

In short, it receives HTTP status code from Apache via http_response_code(), and simply categorize the status code into two categories: Internal Server Error and Non-Internal Server Error. It then passes the category to ErrorPage::GenerateErrorPage() which actually generates contents of the error page.

In ErrorPage::GenerateErrorPage(), I do something like this:

<?php
http_response_code($internal_server_error ? 500 : 404);
?>

at the beginning of the function, so that there won’t be any annoying “headers already sent”. This function will generate a fully functional error page with correct (or what we expected, at least) HTTP status code. After setting the HTTP status code, as you may guess, one of two prepared contents will be generated by following php codes, one for 500, another for 404.

Now let’s go back to your question.

You want to trigger exactly the same error page as Apache does, and now you can simply call the ErrorPage::GenerateErrorPage() from wherever you want, as long as you give it correct parameters (TRUE for 500, FALSE for 404 in my case).

Obviously, because that the Apache error pages are generated by the same function ErrorPage::GenerateErrorPage(), we can guarantee that what you trigger wherever is exactly what you would expect from Apache error pages.

Here is my example of a trigger page:

<?php
ob_start();

require_once("error_page.php");

try
{
    // Actual contents go here
    phpInfo();
    throw new Exception('test exception');
}
catch (Exception $e)
{
    ob_clean();
    ErrorPage::GenerateErrorPage(TRUE);
    ob_end_flush();
    exit();
}

ob_end_flush();
?>

The reason I use ob_start() and ob_clean() is that, in this way, I can clear anything output before the exception occurs, and send a pure 500 Internal Server Error page that looks exactly the same as Apache gives, without any content on the trigger page (phpInfo() in this case). ob_start() and ob_clean() also make sure that there won’t be “headers already sent”, because nothing will ever be sent unless you call ob_end_flush().

The solution above is concluded from what I researched these days. It is so far so good for me, but I’m not sure if it is the correct way to do it. Any comments, questions, thoughts, suggestions and improvements are welcomed.

Это очень хороший вопрос, по многим причинам.

Во-первых, очень хорошо что он сам по себе поставлен. Обычно пользователи РНР не задумываются о таких «мелочах». Но на самом деле об этом должен думать каждый программист, делающий сайты
Во-вторых, здесь мы можем видеть довольно характерный баг Апача, который действительно, почему-то не выполняет директиву ErrorDocument для 500 ошибок, полученных от РНР. Ну и вообще, завязываться на Апач во времена доминирования Нжинкса как-то не очень дальновидно.
В-третьих, как правильно заметил Stalker_RED, сделать редирект при 500 статусе (или 500 статус при редиректе) невозможно — статус может быть только один. Да это и нет смысла делать — проще сразу на месте нужную страницу и прочитать.
В-четвертых, текущий подход, прямо скажем, не очень оптимальный:
— о роботах мы позаботились, о пользователе позаботились, но надо ещё не забыть и программиста. Которому как раз сообщение об ошибке-то нужно видеть во всех подробностях!
— просто отдать нужный НТТР код недостаточно — надо бы ещё и завершить работу скрипта.
— ловить все ошибки вручную через try-catch так себе удовольствие. И код раздувает,и поведение потом быстро не поменяешь. А если в какой-то момент захочется для отладки прикрутить whoops — это придётся по всем блокам бегать?

Чтобы решить все эти проблемы разом, надо сделать единый обработчик ошибок. Который и подробности для программиста залогирует, и нужный заголовок отправит, и красивый хтмл юзеру покажет.

В самом простом варианте это будет что-то вроде такого:

set_exception_handler(function ($e)
{
    error_log($e);
    http_response_code(500);
    if (ini_get('display_errors')) {
        echo $e;
    } else {
        include 'pages/error_500.php';
    }
});

В теории, конечно, можно заменить error handler на глобальный try-catch который оборачивает точку входа, но это менее удобно. Тем более, что для обработки фатальных ошибок нужен свой отдельный обработчик, и в итоге код обработки ошибок начинает занимать довольно значительный объем и лучше конечно его инициализацию вынести отдельно.

  • Предыдующая статья: Делаем собственную страницу ошибки 404

Лого sayt-sozdat.ru

2019-12-01

Здравствуйте, уважаемый посетитель!

Сегодня в рамах рассмотрения системы обработки ошибок выполним необходимые действия по выводу пользователю сообщения о возникновении внутренней ошибки сервера Internal Server Error, соответствующей статусу HTTP 500.

Это необходимо сделать, так как никто не застрахован от возникновения подобных проблем. В таких случаях, если не предпринять соответстующих мер, пользователь в своем браузере будет видеть только лишь какой-нибудь ущербный, неполноценный вариант веб-страницы. Либо вообще пустой экран или страницу в несколько строк с непонятными для него техническими терминами.

И вот для того, чтобы упорядочить работу сайта, обеспечивая пользователя при любых ситуациях необходимой информацией, мы создадим собственную страницу 500.

А затем, для обеспечения на нее перенаправления, сформируем пользовательский обработчик фатальных ошибок PHP. Который в дальнейшем поможет нам обеспечить и другие возможности создаваемого механизма, такие как сохранение логов и отправка сообщений по email.

  • Создание страницы 500
  • Перехват и обработка фатальных ошибок PHP
  • Буферизация вывода в PHP
  • Дополнение файла .htaccess
  • Проверка работы сайта при внутренней ошибке сервера
  • Исходные файлы сайта

Создание страницы 500


В первую очередь создадим в корне сайта новый файл с соответствующим именем, например «page_500.php». И поместим в него код страницы, которая будет отображаться при возникновении ошибки 500. А выполним это аналогично тому, как мы это делали в предыдущей статье при создании страницы 404.

Правда, сделаем это с некоторым отличием, заключающимся в том, что в этот раз при ее формировании будем использовать только разметку HTML, исключая какое-либо использование PHP.

Ведь не логично применять фрагменты кода, которые в случае возникновения фатальной ошибки PHP могут повлиять на отправку страницы, предназначенную, как раз, для обработки таких нестандартных ситуаций.

Конечно, это не относится к применению функции header(), с помощью которой отправляется HTTP заголовок с кодом 500, соответствующий внутренней ошибки сервера (строка 2 в приведенном ниже коде).

kak-vyvesti-stranicu-oshibki-500_1

Рис.1 Файл «page_500.php» с HTML-кодом страницы 500

Как видно, данный вариант по структуре полностью соответствует предыдущей странице 404, но выполнен на чистом HTML. Причем все общие блоки: шапка, меню, основное содержание и футер включены непосредственно, без применения подключающих инструкций PHP.

Что касается оформления, то в данном случае этого не требуется, так HTML-код страницы мало чем отличается от предыдущей. И как следствие, все необходимые свойства уже ранее назначены и добавлены в таблицу стилей CSS.

И в этом можно убедиться, если сейчас открыть созданную страницу через адресную строку браузера, добавив к доменному имени ее адрес /page_500.php. Как и в предыдущем случае в начале сделаем это в обычном, десктопном варианте пользовательского устройства.

Вид созданной страницы 500

Рис.2 Вид созданной страницы 500

А теперь посмотрим как это будет выглядеть при малом разрешении экрана в одно колоночном исполнении.

Вид страницы 500 при малом разрешении экрана

Рис.3 Вид страницы 500 при малом разрешении экрана

Как видно, полученная страница по форме схожа с предыдущей 404. За исключением содержания, отражающего теперь информацию о возникновении внутренней ошибки сервера, соответствующей статусу 500 протокола HTTP.

Таким образом необходимая страница создана. И теперь осталось только обеспечить на нее перенаправление.

Перехват и обработка фатальных ошибок PHP


Как ранее отмечалось, внутренняя ошибка сервера наиболее часто возникает в следствии фатальных ошибок PHP. Причем такие случаи обычно сопровождаются остановкой скрипта. Отчего идентифицировать такую ошибку с помощью того же самого скрипта не получится. Так как в этом случае выполнение в нем каких-либо последующих действий не представляется возможным.

Как вариант решения этой проблемы — применение встроенной функции обратного вызова register_shutdown_function(), предназначенной для регистрации специальной пользовательской функции, не связанной с работой скрипта. И, следовательно, способной выполнить дальнейшие преобразования, несмотря на то, что сам скрипт остановлен.

И таким образом, в случае возникновения фатальной ошибки управление передается этой зарегистрированной функции, являющейся в данном случае обработчиком.

Как может выглядеть регистрация пользовательской функции и перехват в ней последней ошибки, остановившей работу скрипта, показано в следующем фрагменте PHP-кода.

  1. //—-Перехват и обработка фатальных ошибок PHP—-

  2. function fatal_php(){ //Пользовательская функция

  3. $error = error_get_last(); //Получение информации о последней произошедшей ошибке

  4. if ($error !== NULL && in_array($error[‘type’], array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR))){ //Если ошибка произошла и ее тип соответствует фатальной ошибке

  5. $domen = ‘http://’.$_SERVER[‘SERVER_NAME’]; //Домен сайта

  6. header(«Location: $domen/page_500.php»); //Редирект на страницу 500

  7. exit; //Прекращение выполнения текущего скрипта

  8. }

  9. }

  10. register_shutdown_function(‘fatal_php’); //Регистрация пользовательской функции обработчика фатальных ошибок PHP

  11. ?>

Рис.4 Перехват и обработка фатальных ошибок PHP

Здесь все строки кода сопровождаются комментариями, поэтому подробно описывать каждую из них, нет смысла.

Можно лишь отметить, что регистрация пользовательской функции выполняется, как ранее было отмечено, с помощью register_shutdown_function(), расположенной в строке 11.

А сама функция обработчика с именем fatal_php() (поз.3÷10) в начале возвращает ассоциативный массив с описанием последней произошедшей ошибки (функция error_get_last() поз.4). А затем в случае, если выявленная ошибка относится к одному из четырех необходимых типов (E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR), то с помощью функции отправки HTTP-заголовка header() (поз.7) выполняется редирект по указанному аргументом «Location» адресу, соответствующему странице 500.

В случае, если фатальная ошибка PHP возникает в процессе формирования тела страницы при отправленном HTTP-заголовке, то при установках по умолчанию, в соответствии с протоколом HTTP должна возникнуть ошибка Cannot modify header information — headers already sent by (), означающая невозможность изменения заголовка после его отправки. Более подробно об этом и о том, как решить эту проблему мы посмотрим в следующем разделе статьи.

Таким образом при использовании созданной пользовательской функции, в случае, если из-за какой-то критической ошибки PHP-скрипт остановлен, обработчик ее обнаружит и выполнит необходимые действия по ее идентификации и дальнейшей обработке.

В данном случае обработка заключается всего лишь в выполнении редиректа на страницу 500. Но в дальнейшем, когда мы перейдем к сохранению логов и оправке сообщений по email, то здесь же будем использовать и другие, необходимые для этого преобразования.

И последнее, на что необходимо обратить внимание, функция обработчика должна быть расположена в самом начале кода шаблона главной страницы файла index.php. Иными словами, чтобы все остальные PHP-инструкции, используемые при формировании веб-страницы, выполнялись только после ее регистрации. В противном случае при остановке скрипта обработчик не будет вызван и, соответственно, не сможет выполнить свою задачу.

Буферизация вывода в PHP


В созданном обработчике фатальных ошибок PHP (рис.2) с помощью функции HTTP-заголовка header() (поз.7) предусматривается редирект на страницу 500.

Однако, здесь следует учесть одно обстоятельство, а именно: в случае редиректа, выполняемого в момент формирования тела веб-страницы, уже после отправки HTTP-заголовка, непременно должна последовать ошибка Cannot modify header information — headers already sent by ().

Обусловлено это следующим. По умолчанию сервер отправляет в браузер данные веб-страницы по мере их готовности, в процессе выполнения PHP-скрипта. При этом в соответствии с протоколом HTTP, сервер в ответ на запрос должен в первую очередь отправить служебные заголовки, а уж только потом код самого тела страницы. И протоколом HTTP не допускается ситуация, когда в момент передачи тела страницы производится повторная оправка HTTP-заголовка. О чем и говорит описание вышеуказанной ошибки.

В подтверждение этому можно проверить работу созданного обработчика по состоянию на данный момент, с заведомо внесенной критической ошибкой PHP.

На скриншоте показан вариант вывода страницы «Получить скидку», у которой в код PHP файла poluchit-skidku.php специально внесена синтаксическая ошибка.

Ошибка при изменении заголовка после его отправки

Рис.5 Ошибка при изменении заголовка после его отправки

Как видно, здесь в области основного содержания, при обнаружении в ней фатальной ошибки Parse error и остановки скрипта, присутствует также и ошибка Cannot modify header information — headers already sent by (), означающая невозможность изменения заголовка в момент передачи кода данного блока веб-страницы.

А для того, чтобы решить эту проблему и иметь возможность изменять в любой момент HTTP-заголовки, применяется, так называемая буферизация вывода в PHP.

Суть ее в том, что в этом случае при выполнении PHP, сервер не оправляет страницу по мере ее готовности, а складывает полученный код в определенный буфер, параллельно формируя HTTP-заголовки, которые в обычном режиме не допускается оправлять в момент передачи тела страницы.

И только после того, как скрипт выполнит все заложенные в него операции, то всё, что в конечном итоге оказалось в буфере, разом отправляется в браузер пользователя в правильном порядке, как это определенно протоколом HTTP — сначала заголовки, а уж потом страница, сформированная скриптом.

В PHP существуют несколько функций, предназначенных для работы с буфером. Но для данной задачи мы будем использовать только две из них ob_start() — для включения буферизации вывода и ob_end_flush() — для отправки данных из буфера и отключения буферизации.

Схематично для генерируемой HTML-страницы это можно представить следующим образом.

kak-vyvesti-stranicu-oshibki-500_2

Рис.6 Буферизация вывода в PHP

А ниже показано, как в итоге будет выглядеть код шаблона главной страницы в файле index.php после дополнения его обработчиком фатальных ошибок PHP и элементами буферизации вывода PHP (светлым фоном обозначены дополнительные фрагмента кода).

kak-vyvesti-stranicu-oshibki-500_3

Рис.7 Файл index.php с обработчиком ошибок и буферизацией вывода

Следует отметить, что для оптимизации файла index.php, ранее размещенный в начале шаблона главной страницы PHP-код, предназначенный для получения данных при формировании динамической страницы, перенесен в файл start.php, который подключается соответствующей инструкцией в строке 13.

Таким образом буферизацию вывода HTML-страницы, генерированной скриптом PHP, мы выполнили. Однако, для полноценной работы сайта при обработке ошибки 500 необходимо сделать еще одно небольшое дополнение, которые мы сейчас и рассмотрим.

Дополнение файла .htaccess


Приведенные выше преобразования предназначены для выполнения редиректа на страницу 500 в случае прерывания работы скрипта при фатальных ошибках PHP.

Но для того, чтобы это происходило и в других случаях внутренней ошибки сервера, необходимо в файл .htaccess добавить директиву ErrorDocument, аналогичную той, которую мы использовали ранее при редиректе на страницу 404. Только теперь в ней должен быть указан соответствующий адрес /page_500.php.

А заодно, в целях безопасности полезно будет вообще отключить отображение системных сообщений на экране пользователя. Так как теперь возникающие по каким-либо причинам ошибки будут фиксироваться собственным механизмом обработки ошибок и нет необходимости их выводить в браузер. Тем более, что в определенных случаях такая излишняя для пользователя информация может быть использована недоброжелателями в качестве уязвимости сайта.

В итоге файл .htaccess следует дополнить следующими директивами, которые обеспечат выполнение вышеперечисленных действий.

  1. ErrorDocument 500 /page_500.php

  2. php_flag display_errors 0

Рис.8 Редирект 500 в файле .htaccess

Таким образом мы сделали все необходимые преобразования для вывода страницы 500. И теперь можно проверить, как это в реальности будет работать.

Проверка работы сайта при внутренней ошибке сервера


Проверку обработки внутренней ошибки сервера выполним на примере возникновения фатальной ошибки PHP, что позволит удостовериться в корректной работе, как созданного обработчики фатальных ошибок, так и процесса буферизации вывода генерируемой страницы и редиректа на страницу 500.

Для этого в код PHP временно внесем ту же самую синтаксическую ошибку, которую ранее мы делали на промежуточном этапе (рис.5). И посмотрим, как теперь будет обработана такая ситуация.

Вывод страницы 500 при фатальной ошибке PHP

Рис.9 Вывод страницы 500 при фатальной ошибке PHP

Как видно, теперь критическая ошибка отработана должным образом, с перенаправлением на страницу ошибки 500.

При желании, можно проверить работу сайта и при других искусственно созданных фатальных ошибках. И во всех случаях результат должен быть один — отображение собственной страницы 500. Что в итоге и требовалось получить.

В следующей статье мы создадим механизм обработки не фатальных ошибок PHP, где с помощью собственного обработчика будет обеспечиваться их перехват и сохранение сообщений в соответствующем журнале.

.

Исходные файлы сайта


Знак папкиИсходные файлы сайта с обновлениями, которые были сделаны в данной статье, можно скачать из прилагаемых дополнительных материалов:

  • Файлы каталога www
  • Таблицы базы данных MySQL

Дополнительные материалы бесплатно предоставляются только зарегистрированным пользователям.

Для скачивания исходных файлов необходимо авторизоваться под своим аккаунтом через соответствующую форму.

Для тех кто не зарегистрирован, можно это сделать на вкладке Регистрация.

С уважением,

  • Следующая сатья: Перехват и обработка не фатальных ошибок PHP

Если у Вас возникли вопросы, или есть какие-либо пожелания по представлению материала, либо заметили какие-нибудь ошибки, а быть может просто хотите выразить свое мнение, пожалуйста, оставьте свои комментарии. Такая обратная связь очень важна для возможности учета мнения посетителей.

Буду Вам за это очень признателен!

Reason behind the php errorThe PHP error 500 can be considered a general error that doesn’t indicate a particular problem. It simply lets you know that there was an internal server error that didn’t allow your request to be completed. As the message isn’t clear enough, this article has been penned down to inform you about a variety of possible causes and solutions related to the 500 internal server error.

Read till the end to find the reason behind the PHP error 500 and resolve it at the earliest.

Contents

  • How To Solve 500 Internal Server Error in PHP
    • – How To Get More Details About the Error
    • – Get an Error Message Coding Example
  • Possible Causes of PHP Error 500
  • Cause of Htaccess Internal Server Error
    • – How To Remove the htaccess Internal Server Error
  • PHP Code Time-out
    • – Solving the PHP Code Time Out Error
  • Insufficient PHP Memory Sending 500 Error Message
    • – How To Increase the PHP Memory Limit
  • Incorrect File Permissions
    • – Which File Permission Loads the File Successfully?
    • – A Fact To Remember
  • Changes in the Code
    • – Deal With the Recent Code Changes
  • The Browser Cookies
    • – Deleting the Browser Cookies
  • Browser Cache
    • – Clearing the Browser Cache
  • 500 Internal Server Error on WordPress Websites
    • – Plugins or Themes Causing the PHP Error 500
  • Conclusion

How To Solve 500 Internal Server Error in PHP

You can solve the 500 internal server error in various ways depending on the cause of the stated error. Here, you should begin with getting a closer view of the issue before solving it. Therefore, you’ll need to turn on error reporting to get more details about the given error.

– How To Get More Details About the Error

Open your PHP file and pass “E_ALL” to the error_reporting function to get an error message instead of a general PHP error 500. Next, you’ll need to turn on the display_errors and the display_startup_errors settings after ensuring that you aren’t using a production server.

Also, don’t forget to disable the display_errors setting and enable the log_errors setting before deploying your website. It is because the former setting isn’t recommended to be used on production servers.

– Get an Error Message Coding Example

For instance, you cannot figure out the actual cause of the 500 error. Therefore, you’ll turn on error reporting and display the errors to understand them better.

Please add the below block of code in your PHP file to get a clearer error message:

error_reporting(E_ALL);
ini_set(‘display_errors’, 1);
ini_set(‘display_startup_errors’, 1);

Possible Causes of PHP Error 500

As the 500 internal server error doesn’t appear due to a single reason, listed below are some possible reasons that might be responsible for its occurrence:

  • The htacess misconfiguration
  • A possible coding time out
  • Insufficient PHP memory
  • Incorrect file permissions
  • Recently added code
  • The browser cookies
  • The browser cache

Go through the below sections to gain in-depth knowledge about the above-stated problems and their solutions.

Cause of Htaccess Internal Server Error

The .htaccess file, also known as the “distributed configuration file” is used to specify some particular directives for the contents of a directory where it is located. So, are you using this kind of file? If yes, try rechecking the structure and syntax inside the given file. It is because any syntax errors or misconfiguration can result in a 500 internal server error.

What else can you do? Read below:

– How To Remove the htaccess Internal Server Error

You can remove the htaccess internal server error by renaming the .htaccess file or simply removing the given file for some time to confirm if it is causing the 500 error. Moreover, it would be beneficial to note that an empty .htaccess file can throw the same error as well.

The above solutions are the easiest ways to confirm the stated cause when you aren’t able to identify the errors in the .htaccess file. If the error continues to pop up, look for more causes and solutions below.

PHP Code Time-out

A PHP code time-out can be defined as an interrupting signal generated either by a program or a device after a long waiting period. Hence, if your PHP script contains a lot of external links and they are slow to respond, then an HTTP error 500 PHP is displayed on your browser. Does this case seem to be similar to yours? Then here are the solutions that can be helpful for you:

– Solving the PHP Code Time Out Error

You can make the PHP code time-out error go away by removing the external connections from your script file. However, if you can’t afford to remove the external links, then you can increase the waiting period. Here, all you have to do is open your php.ini file and set the max_execution_time to any number of seconds within 180. Also, remember that the default value of the same is set to 60 seconds.

Insufficient PHP Memory Sending 500 Error Message

Certainly, the PHP scripts take up a specific amount of memory for successful execution. Hence, there can be a possibility of the memory limit being exceeded in certain cases. Consequently, you might be seeing the 500 error message due to insufficient memory.

– How To Increase the PHP Memory Limit

Similar to the max_execution_time, the memory_limit can also be specified in the php.ini file. However, please note that you can’t assign a value greater than 256M to the memory_limit setting.

It would be beneficial to know that the memory_limit has its default value set to 129M. So, if you feel like the given memory limit isn’t enough for your PHP scripts to run successfully, then you can increase it.

Incorrect File Permissions

Do you know that incorrect file permission can make the PHP error 500 appear on your screen? Well, it would be great to note that different kinds of permissions can be assigned to the files. So, maybe, the file that you are trying to load on your browser doesn’t have permission to be read or executed by you.

– Which File Permission Loads the File Successfully?

The 644 file permission loads the file successfully. It is because the 644 permission allows every user to read the file with ease. However, if you want to perform a function such as uploading an image, then the 755 file permission will work for you.

Note that the 755 file permission allows the users to read as well as execute the required file.

– A Fact To Remember

On most of the Operating Systems, only the owner of the file is allowed to change the file permission.

Changes in the Code

Is the PHP error 500 appearing while loading a file that was previously working fine? Then think about any recent code changes that have been done in the stated file. Indeed, some invalid pieces of code can be a reason for the 500 internal server error to display on your screen. Well, if you haven’t made any changes, then reach out to your team members who have access to the same file and ask them about the same.

– Deal With the Recent Code Changes

Certainly, you’ll need to remove the recent code changes to see if the given changes are the root cause of the HTTP error 500 PHP. But here, a better idea can be to have two files: one with the changed code and another with the code that worked fine previously. Next, you’ll have to run both of the files to confirm the cause of the error. And the benefit of creating two files will be that you won’t end up losing the essential changes that you made if they aren’t erroneous.

The Browser Cookies

But where are the browser cookies created and who creates them? Well, the browser cookies are created by the web servers during your browsing routine. And you can find these little data stores stored on your browser.

Undeniably, the HTTP cookies enhance your browsing experience on various websites. But they can be a source of a 500 internal server error as well when the data stored in them is outdated.

– Deleting the Browser Cookies

As stated earlier, the browser cookies are stored on your browser. So, you can go to the settings of your browser, find the cookies, and delete them. Next, you’ll need to restart your browser and try loading the file that was facing the 500 error earlier. Hopefully, you’ll get the file loaded after deleting the cookies.

Browser Cache

Have you noticed that the websites load faster the next time you visit them as compared to the very first time? Undoubtedly, the website loading time is decreased because of the browser cache stored in your hard drive. But how can it be connected with the annoying HTTP error 500 PHP? So, here is the answer:

As the websites are updated time by time, the issue can be a mismatch between the cache created for the websites and the actual websites, leading to a 500 error.

– Clearing the Browser Cache

Undeniably, the act of clearing the browser cache isn’t harmful. Moreover, if the browser cache is the cause behind the 500 error, then it’s not a good idea to keep it. So, proceed with clearing the browser cache, and it will allow your browser to load the updated website efficiently.

500 Internal Server Error on WordPress Websites

Are you encountering a 500 error on your WordPress website? Then read below to find the areas that might be causing the same error to pop up. However, it would be best for you to begin with loading the admin panel to ensure that the issue resides within the technical stuff being used in website creation.

– Plugins or Themes Causing the PHP Error 500

Indeed, the plugins are used to create feature-rich websites, and the themes are the dress codes that beautify the overall look of your website. But unfortunately, not all plugins and themes come with an error-free code. Therefore, if your admin panel is working fine, try deactivating the currently activated plugins and themes one after the other to find the cause of the 500 error.

Conclusion

Certainly, the PHP error 500 is a general error, but luckily, you have learned about all the possible reasons that might be causing the same error. Moreover, you have got a list of solutions in the shape of this article to help you out whenever you get stuck with the 500 error on your screen. Also, the below points have been penned down to summarize all the solutions to boost your error-solving process:

  • You can get a closer view of the PHP error 500 by turning on the error reporting setting to display all errors.
  • You can solve the PHP error 500 by temporarily deleting the misconfigured htaccess file.
  • The 500 error can go away by increasing the values set for the max_execution_time and the memory_limit settings.
  • Setting the file permission to 644 or 755 can help in resolving the 500 internal server error.
  • You can try removing the recent code changes to see if the 500 error goes away. You can also delete the cookies, and the browser cache can help resolve the 500 error.
  • The poorly-coded plugins and themes can cause a 500 error on WordPress websites.

Php errorEnding this article with a satisfactory note that now, you won’t feel frustrated while seeing PHP error 500 on your browser window because you are fully prepared to handle it.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

Понравилась статья? Поделить с друзьями:
  • Php отловить ошибки
  • Php отладка ошибок
  • Photon launcher phasmophobia произошла одна или несколько ошибок
  • Philips saeco syntia коды ошибок
  • Peugeot 308 ошибка abs