Php показывать ошибку 500

I have installed a PHP application onto a shared hosting web server. I am getting a 500 Internal Server Error. I don’t seem to have access to any log files so I would like the error page to temporarily give details of the error.

miken32's user avatar

miken32

42k16 gold badges111 silver badges154 bronze badges

asked Nov 17, 2009 at 20:36

tpower's user avatar

try:

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

at the top of the file.

answered Nov 17, 2009 at 20:38

Jeremy Morgan's user avatar

1

If Jeremy Morgan’s solution doesn’t work, try creating your own log file using set_error_handler(). Usually some information about the state of the application ($GLOBALS and so on) can be enough information, but PHP will (at least try to) pass you all sorts of information about where the error occurred and what type of error it is.

Also, try using the «Divide And Conquer» method of debugging. Start with about half of your file, and then expand upward if it’s still crashing or downward if it runs umtil that point. If you don’t want to remove your code, either /* comment out */ the code to be cut, or use the __halt_compiler() special directive to have PHP ignore all remaining data in the file.

Finally, one thing that drove me mad trying to fix it is what’s called a Byte Order Mark. PHP was evaluating that BOM at the beginning of the file, causing it to send output, and causing problems while trying to send headers and the like. Probably not what your issue is, but knowledge worth having.

answered Nov 17, 2009 at 20:48

Dereleased's user avatar

DereleasedDereleased

9,9393 gold badges36 silver badges51 bronze badges

1

I doubt you’re getting that error from PHP. On shared hosting it’s more likely that the application’s default .htaccess config is causing the error.

My guess would be a mod_rewrite without a RewriteBase set.

answered Nov 17, 2009 at 20:40

Tim Lytle's user avatar

Tim LytleTim Lytle

17.5k10 gold badges60 silver badges91 bronze badges

2

look at the values in phpinfo(); to see if anything sticks out… put it somewhere in the code and it should display a bunch of php version information

answered Nov 17, 2009 at 20:43

CheeseConQueso's user avatar

CheeseConQuesoCheeseConQueso

5,83129 gold badges93 silver badges126 bronze badges

An «Internal Server Error» is not a PHP error (as the name says). Therefore, you either have to look at your server logs (which you do not have access to, as it seems) or you can’t do anything about it from PHP.

answered Nov 17, 2009 at 20:40

Franz's user avatar

FranzFranz

11.4k8 gold badges48 silver badges70 bronze badges

2

I have installed a PHP application onto a shared hosting web server. I am getting a 500 Internal Server Error. I don’t seem to have access to any log files so I would like the error page to temporarily give details of the error.

miken32's user avatar

miken32

42k16 gold badges111 silver badges154 bronze badges

asked Nov 17, 2009 at 20:36

tpower's user avatar

try:

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

at the top of the file.

answered Nov 17, 2009 at 20:38

Jeremy Morgan's user avatar

1

If Jeremy Morgan’s solution doesn’t work, try creating your own log file using set_error_handler(). Usually some information about the state of the application ($GLOBALS and so on) can be enough information, but PHP will (at least try to) pass you all sorts of information about where the error occurred and what type of error it is.

Also, try using the «Divide And Conquer» method of debugging. Start with about half of your file, and then expand upward if it’s still crashing or downward if it runs umtil that point. If you don’t want to remove your code, either /* comment out */ the code to be cut, or use the __halt_compiler() special directive to have PHP ignore all remaining data in the file.

Finally, one thing that drove me mad trying to fix it is what’s called a Byte Order Mark. PHP was evaluating that BOM at the beginning of the file, causing it to send output, and causing problems while trying to send headers and the like. Probably not what your issue is, but knowledge worth having.

answered Nov 17, 2009 at 20:48

Dereleased's user avatar

DereleasedDereleased

9,9393 gold badges36 silver badges51 bronze badges

1

I doubt you’re getting that error from PHP. On shared hosting it’s more likely that the application’s default .htaccess config is causing the error.

My guess would be a mod_rewrite without a RewriteBase set.

answered Nov 17, 2009 at 20:40

Tim Lytle's user avatar

Tim LytleTim Lytle

17.5k10 gold badges60 silver badges91 bronze badges

2

look at the values in phpinfo(); to see if anything sticks out… put it somewhere in the code and it should display a bunch of php version information

answered Nov 17, 2009 at 20:43

CheeseConQueso's user avatar

CheeseConQuesoCheeseConQueso

5,83129 gold badges93 silver badges126 bronze badges

An «Internal Server Error» is not a PHP error (as the name says). Therefore, you either have to look at your server logs (which you do not have access to, as it seems) or you can’t do anything about it from PHP.

answered Nov 17, 2009 at 20:40

Franz's user avatar

FranzFranz

11.4k8 gold badges48 silver badges70 bronze badges

2

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!

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

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Phpbb ошибка http
  • Php получить текст ошибки
  • Php уровни ошибок
  • Php получить ошибку fopen
  • Php получить ошибку curl

  • Добавить комментарий

    ;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: