Php ошибка 500 как вывести

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

Rob's user avatar

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's user avatar

Davide

1,6251 gold badge16 silver badges29 bronze badges

answered Apr 22, 2010 at 1:49

awgy's user avatar

awgyawgy

16.5k4 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's user avatar

Matthew Lock

13k12 gold badges91 silver badges130 bronze badges

answered May 25, 2016 at 3:53

Aaron's user avatar

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

dtbarne's user avatar

dtbarnedtbarne

8,0805 gold badges43 silver badges49 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

Max's user avatar

MaxMax

2,5211 gold badge23 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

von verletzt's user avatar

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 Nguyen's user avatar

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

WoodrowShigeru's user avatar

WoodrowShigeruWoodrowShigeru

1,3771 gold badge16 silver badges23 bronze badges

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

Rob's user avatar

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's user avatar

Davide

1,6251 gold badge16 silver badges29 bronze badges

answered Apr 22, 2010 at 1:49

awgy's user avatar

awgyawgy

16.5k4 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's user avatar

Matthew Lock

13k12 gold badges91 silver badges130 bronze badges

answered May 25, 2016 at 3:53

Aaron's user avatar

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

dtbarne's user avatar

dtbarnedtbarne

8,0805 gold badges43 silver badges49 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

Max's user avatar

MaxMax

2,5211 gold badge23 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

von verletzt's user avatar

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 Nguyen's user avatar

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

WoodrowShigeru's user avatar

WoodrowShigeruWoodrowShigeru

1,3771 gold badge16 silver badges23 bronze badges

  • Предыдующая статья: Делаем собственную страницу ошибки 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

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

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

Этого никогда раньше не было. Обычно он отображает ошибку, но теперь она просто дает мне 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)

This is a short guide on how to send a 500 Internal Server Error header to the client using PHP. This is useful because it allows us to tell the client that the server has encountered an unexpected condition and that it cannot fulfill the request.

Below, I have created a custom PHP function called internal_error.

//Function that sends a 500 Internal Server Error status code to
//the client before killing the script.
function internal_error(){
    header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500);
    echo '<h1>Something went wrong!</h1>';
    exit;
}

When the PHP function above is called, the script’s execution is halted and “Something went wrong!” is printed out onto the page.

Furthermore, if you inspect the HTTP headers with your browser’s developer console, you will see that the function is returning a 500 Internal Server Error status code:

500 Internal Server Error

Google’s Developer Tools showing the 500 Internal Server Error status that was returned.

To send the 500 status code, we used PHP’s header function like so:

//Send a 500 status code using PHP's header function
header($_SERVER["SERVER_PROTOCOL"] . ' 500 Internal Server Error', true, 500);

Note that we used the SERVER_PROTOCOL variable in this case because the client might be using HTTP 1.0 instead of HTTP 1.1. In other examples, you will find developers making the assumption that the client will always be using HTTP 1.1.

This is not the case.

The problem with PHP is that it doesn’t always send a 500 Internal Server Error when an exception is thrown or a fatal error occurs.

This can cause a number of issues:

  1. It becomes more difficult to handle failed Ajax calls, as the server in question is still responding with a 200 OK status. For example: The JQuery Ajax error handling functions will not be called.
  2. Search engines such as Google may index your error pages. If this happens, your website may lose its rankings.
  3. Other HTTP clients might think that everything is A-OK when it is not.

Note that if you are using PHP version 5.4 or above, you can use the http_response_code function:

//Using http_response_code
http_response_code(500);

Far more concise!

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

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

Если проблема в файле .htaccess — сообщение Internal Server Error.

Часто ошибку 500 можно легко устранить даже не имея знаний в области веб-разработки. О том, как это сделать, расскажем далее.

Ошибки в файле .htaccess

Сообщение Internal Server Error выводится, когда в файле .htaccess есть ошибки. Переименуйте файл .htaccess и проверьте корректность работы сайта. Если он доступен, удалите правила, которые были добавлены последними, или восстановите старый файл из резервной копии.

Ошибки в скриптах сайта

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

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

Нажмите сочетание клавиш Ctrl+Shift+I или используйте меню браузера:

  • Mozilla Firefox — «Веб-разработка» → «Инструменты разработчика»;
  • Google Chrome — «Дополнительные инструменты» → «Инструменты разработчика»;
  • Opera — «Разработка» → «Инструменты разработчика».

Перейдите во вкладку «Сеть (Network)». На ошибку 500 указывает соответствующее число в колонке «Статус».

Статус пустой страницы может быть и 200 (Ok). В таком случае проверьте, есть ли содержимое в индексном файле сайта, очистите кеш вашей CMS. Если ранее сайт работал корректно, восстановите его из резервной копии.

Вывод ошибок на сайте

Вывод ошибок PHP на хостинге по умолчанию выключен. Чтобы увидеть их текст, добавьте в файл .htaccess правило: php_value display_errors 1 и обновите страницу сайта.

Если текст не отобразился, включите вывод ошибок через конфигурационный файл CMS. Он расположен в корневой директории сайта.

WordPress

Замените в файле wp-config.php строку define(‘WP_DEBUG’, false); на define(‘WP_DEBUG’, true);

Joomla

Измените значение переменных debug и error_reporting в configuration.php на: public $debug = '1'; и public $error_reporting = 'maximum';

1С-Битрикс

В конфигурационном файле по пути ~/public_html/bitrix/php_interface/dbconn.php замените значение переменных DBDebug и DBDebugToFile на: $DBDebug = true; и $DBDebugToFile = true;

Laravel

В файле .env измените APP_DEBUG=false на APP_DEBUG=true

Алгоритм устранения ошибки можно найти в интернете, поместив ее текст в строку любой поисковой системы. Если с помощью найденной информации возобновить работу сайта не получится, восстановите его из резервной копии. Наши специалисты могут помочь с восстановлением. Для этого направьте обращение из раздела «Поддержка» Панели управления.

Журнал ошибок PHP

Иногда ошибка не выводится на странице или возникает периодически: ее тяжело отследить. Чтобы узнать текст таких ошибок, записывайте информацию о них в файл — журнал ошибок PHP. Подключите его, добавив в .htaccess строку: php_value error_log /home/username/domains/domain.ru/php_errors.log и обновите страницу сайта.

Откройте создавшийся файл журнала с помощью Файлового менеджера в Панели управления. Чтобы просматривать возникающие ошибки в реальном времени, отметьте опцию «Включить автообновление».

Быстро возобновить работу сайта можно, восстановив его из резервной копии за дату, когда ошибок не было. Если восстановление нежелательно, обратитесь к разработчику.

Для устранения некоторых ошибок не требуется специальных знаний. Рассмотрим самые распространенные.

Нехватка оперативной памяти

Ошибка с текстом Allowed memory size возникает из-за нехватки оперативной памяти для выполнения скрипта: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 81 bytes) in /home/username/domains/domain.ru/public_html/somescript.php

Чтобы исправить ее, увеличьте лимит оперативной памяти, добавив в файл .htaccess директиву:

php_value memory_limit 512M

Вместо «512» укажите необходимый объем памяти. Максимальное значение ограничивается тарифом.

Текст Out of memory означает, что достигнут лимит оперативной памяти по тарифному плану:

PHP Fatal error: Out of memory (allocated 39059456) (tried to allocate 262144 bytes) in /home/username/domains/domain.ru/public_html/somescript.php

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

Ошибки в CMS

При обновлении CMS случаются синтаксические ошибки:

PHP Parse error: syntax error, unexpected '[', expecting ')' in /home/username/domains/domain.ru/public_html/wp-content/plugins/wordpress-23-related-posts-plugin/config.php on line 130

Это происходит из-за того, что новые функции CMS не поддерживают устаревшие версии PHP. Чтобы исправить ошибку, измените версию PHP для сайта на более современную в разделе «Сайты» → «Веб-серверы».

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

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

Была ли эта инструкция полезной?

(PHP 5 >= 5.4.0, PHP 7, PHP 8)

http_response_codeGet or Set the HTTP response code

Description

http_response_code(int $response_code = 0): int|bool

Parameters

response_code

The optional response_code will set the response code.

Return Values

If response_code is provided, then the previous
status code will be returned. If response_code is not
provided, then the current status code will be returned. Both of these
values will default to a 200 status code if used in a web
server environment.

false will be returned if response_code is not
provided and it is not invoked in a web server environment (such as from a
CLI application). true will be returned if
response_code is provided and it is not invoked in a
web server environment (but only when no previous response status has been
set).

Examples

Example #1 Using http_response_code() in a web server environment


<?php// Get the current response code and set a new one
var_dump(http_response_code(404));// Get the new response code
var_dump(http_response_code());
?>

The above example will output:

Example #2 Using http_response_code() in a CLI environment


<?php// Get the current default response code
var_dump(http_response_code());// Set a response code
var_dump(http_response_code(201));// Get the new response code
var_dump(http_response_code());
?>

The above example will output:

bool(false)
bool(true)
int(201)

See Also

  • header() — Send a raw HTTP header
  • headers_list() — Returns a list of response headers sent (or ready to send)

craig at craigfrancis dot co dot uk

11 years ago


If your version of PHP does not include this function:

<?phpif (!function_exists('http_response_code')) {
        function
http_response_code($code = NULL) {

            if (

$code !== NULL) {

                switch (

$code) {
                    case
100: $text = 'Continue'; break;
                    case
101: $text = 'Switching Protocols'; break;
                    case
200: $text = 'OK'; break;
                    case
201: $text = 'Created'; break;
                    case
202: $text = 'Accepted'; break;
                    case
203: $text = 'Non-Authoritative Information'; break;
                    case
204: $text = 'No Content'; break;
                    case
205: $text = 'Reset Content'; break;
                    case
206: $text = 'Partial Content'; break;
                    case
300: $text = 'Multiple Choices'; break;
                    case
301: $text = 'Moved Permanently'; break;
                    case
302: $text = 'Moved Temporarily'; break;
                    case
303: $text = 'See Other'; break;
                    case
304: $text = 'Not Modified'; break;
                    case
305: $text = 'Use Proxy'; break;
                    case
400: $text = 'Bad Request'; break;
                    case
401: $text = 'Unauthorized'; break;
                    case
402: $text = 'Payment Required'; break;
                    case
403: $text = 'Forbidden'; break;
                    case
404: $text = 'Not Found'; break;
                    case
405: $text = 'Method Not Allowed'; break;
                    case
406: $text = 'Not Acceptable'; break;
                    case
407: $text = 'Proxy Authentication Required'; break;
                    case
408: $text = 'Request Time-out'; break;
                    case
409: $text = 'Conflict'; break;
                    case
410: $text = 'Gone'; break;
                    case
411: $text = 'Length Required'; break;
                    case
412: $text = 'Precondition Failed'; break;
                    case
413: $text = 'Request Entity Too Large'; break;
                    case
414: $text = 'Request-URI Too Large'; break;
                    case
415: $text = 'Unsupported Media Type'; break;
                    case
500: $text = 'Internal Server Error'; break;
                    case
501: $text = 'Not Implemented'; break;
                    case
502: $text = 'Bad Gateway'; break;
                    case
503: $text = 'Service Unavailable'; break;
                    case
504: $text = 'Gateway Time-out'; break;
                    case
505: $text = 'HTTP Version not supported'; break;
                    default:
                        exit(
'Unknown http status code "' . htmlentities($code) . '"');
                    break;
                }
$protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');header($protocol . ' ' . $code . ' ' . $text);$GLOBALS['http_response_code'] = $code;

            } else {

$code = (isset($GLOBALS['http_response_code']) ? $GLOBALS['http_response_code'] : 200);

            }

            return

$code;

        }
    }

?>

In this example I am using $GLOBALS, but you can use whatever storage mechanism you like... I don't think there is a way to return the current status code:

https://bugs.php.net/bug.php?id=52555

For reference the error codes I got from PHP's source code:

http://lxr.php.net/opengrok/xref/PHP_5_4/sapi/cgi/cgi_main.c#354

And how the current http header is sent, with the variables it uses:

http://lxr.php.net/opengrok/xref/PHP_5_4/main/SAPI.c#856


Stefan W

9 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

9 years ago


You can also create a enum by extending the SplEnum class.
<?php/** HTTP status codes */
class HttpStatusCode extends SplEnum {
    const
__default = self::OK;

        const

SWITCHING_PROTOCOLS = 101;
    const
OK = 200;
    const
CREATED = 201;
    const
ACCEPTED = 202;
    const
NONAUTHORITATIVE_INFORMATION = 203;
    const
NO_CONTENT = 204;
    const
RESET_CONTENT = 205;
    const
PARTIAL_CONTENT = 206;
    const
MULTIPLE_CHOICES = 300;
    const
MOVED_PERMANENTLY = 301;
    const
MOVED_TEMPORARILY = 302;
    const
SEE_OTHER = 303;
    const
NOT_MODIFIED = 304;
    const
USE_PROXY = 305;
    const
BAD_REQUEST = 400;
    const
UNAUTHORIZED = 401;
    const
PAYMENT_REQUIRED = 402;
    const
FORBIDDEN = 403;
    const
NOT_FOUND = 404;
    const
METHOD_NOT_ALLOWED = 405;
    const
NOT_ACCEPTABLE = 406;
    const
PROXY_AUTHENTICATION_REQUIRED = 407;
    const
REQUEST_TIMEOUT = 408;
    const
CONFLICT = 408;
    const
GONE = 410;
    const
LENGTH_REQUIRED = 411;
    const
PRECONDITION_FAILED = 412;
    const
REQUEST_ENTITY_TOO_LARGE = 413;
    const
REQUESTURI_TOO_LARGE = 414;
    const
UNSUPPORTED_MEDIA_TYPE = 415;
    const
REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const
EXPECTATION_FAILED = 417;
    const
IM_A_TEAPOT = 418;
    const
INTERNAL_SERVER_ERROR = 500;
    const
NOT_IMPLEMENTED = 501;
    const
BAD_GATEWAY = 502;
    const
SERVICE_UNAVAILABLE = 503;
    const
GATEWAY_TIMEOUT = 504;
    const
HTTP_VERSION_NOT_SUPPORTED = 505;
}


Rob Zazueta

10 years ago


The note above from "Anonymous" is wrong. I'm running this behind the AWS Elastic Loadbalancer and trying the header(':'.$error_code...) method mentioned above is treated as invalid HTTP.

The documentation for the header() function has the right way to implement this if you're still on < php 5.4:

<?php
header
("HTTP/1.0 404 Not Found");
?>


Anonymous

10 years ago


If you don't have PHP 5.4 and want to change the returned status code, you can simply write:
<?php
header
(':', true, $statusCode);
?>

The ':' are mandatory, or it won't work

divinity76 at gmail dot com

3 years ago


if you need a response code not supported by http_response_code(), such as WebDAV / RFC4918's "HTTP 507 Insufficient Storage", try:

<?php
header
($_SERVER['SERVER_PROTOCOL'] . ' 507 Insufficient Storage');
?>
result: something like

HTTP/1.1 507 Insufficient Storage


Steven

8 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

9 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

5 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

7 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

8 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);
}


Ошибка 500, также известная как внутренняя ошибка сервера, – это общее сообщение об ошибке, которое указывает на проблему с сервером веб-сайта. Эта ошибка может возникать по разным причинам, например, из-за проблем с конфигурацией сервера, проблем с кодом сайта или проблем с самим сервером.

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

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

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

error_reporting(E_ALL);
ini_set('display_errors', 1);

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

Чтобы включить вывод ошибок php добавьте в .htaccess файл:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_value docref_root 1
php_value docref_ext 1

Показать все ошибки кроме предупреждений (Notice):

php_flag display_errors On
php_value error_reporting "E_ALL & ~E_NOTICE"

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

Для того чтобы проверить журналы ошибок, вы можете проверить журналы на сервере или в некоторых случаях ваш хостинг-провайдер предоставит вам доступ к журналам в своей панели управления.

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

Данная статья сгенерирована ChatGPT))

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 ini
  • Phpmyadmin config inc php ошибка
  • Php отображать все ошибки в браузере
  • Phpmailer ошибка сервера номер 500
  • Php отключить ошибки в файле