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
42k16 gold badges111 silver badges154 bronze badges
asked Nov 17, 2009 at 20:36
try:
error_reporting(E_ALL);
ini_set('display_errors', '1');
at the top of the file.
answered Nov 17, 2009 at 20:38
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
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 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
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
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
42k16 gold badges111 silver badges154 bronze badges
asked Nov 17, 2009 at 20:36
try:
error_reporting(E_ALL);
ini_set('display_errors', '1');
at the top of the file.
answered Nov 17, 2009 at 20:38
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
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 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
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
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:
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:
- 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.
- Search engines such as Google may index your error pages. If this happens, your website may lose its rankings.
- 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, он обычно видит в своем браузере сообщение, похожее на “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))
Этого никогда раньше не было. Обычно он отображает ошибку, но теперь она просто дает мне 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)

