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,5311 gold badge23 silver badges28 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,3871 gold badge16 silver badges23 bronze badges

Доброго времени. Если при ошибках в php коде возникали оповещения на подобии:
Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘test.wrongtable’ doesn’t exist in /tmp/pdo_test.php on line 18
То сейчас любая ошибка в коде приводит к ошибке сервера (500).

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

В файле .htaccess прописано лишь пару строк:
AddDefaultCharset UTF-8
DirectoryIndex index.php

Большое спасибо за внимание!


  • Вопрос задан

    более трёх лет назад

  • 596 просмотров

Пригласить эксперта

попробуйте добавить в .htaccess

php_flag display_errors On
php_value error_log /path/to/error.log
php_value error_reporting “E_ALL & ~E_NOTICE”

UPD.
если в логах php пусто, посмотрите ещё логи апача

у вас таблицы wrongtable в базе test нет, потому и вылетает

Warning: PDO::query(): SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘test.wrongtable’ doesn’t exist in /tmp/pdo_test.php on line 18

судя по всему ее забыли создать


  • Показать ещё
    Загружается…

08 июн. 2023, в 12:24

1500 руб./в час

12 июн. 2023, в 12:01

40000 руб./за проект

12 июн. 2023, в 11:51

500 руб./за проект

Минуточку внимания

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

What you placed at the top of your PHP.INI file is what you would use in an actual .php file to turn on error reporting / show errors on a per file bases. You do not add that to your PHP.INI file.

Example of use in a .php file:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');

If you search your PHP.INI file you will find error_reporting = E_ALL, and display_errors = On are set.

Notice the definitions in the PHP.INI file:

; This directive controls whether or not and where PHP will output errors,
; notices and warnings too. Error output is very useful during development, but
; it could be very dangerous in production environments. Depending on the code
; which is triggering the error, sensitive information could potentially leak
; out of your application such as database usernames and passwords or worse.
; For production environments, we recommend logging errors rather than
; sending them to STDOUT.
; Possible Values:
;   Off = Do not display any errors
;   stderr = Display errors to STDERR (affects only CGI/CLI binaries!)
;   On or stdout = Display errors to STDOUT
; Default Value: On
; Development Value: On
; Production Value: Off
; http://php.net/display-errors
display_errors = On

You should not display errors in a production environment. You don’t want to reveal any extra information to any potential hackers. Also these errors will mean nothing to your users. You should just show a generic error page and log all your errors for your review.

In a development environment I would have them all on and display_startup_errors = On.

I see log_errors = On so you should be getting your error messages logged to:
/var/log/nginx/default-error.log. I suggest looking there to find your issue after you fix your PHP.INI file.

Как включить отображение PHP ошибок для сайта?

Как включить вывод PHP ошибок на сайте? Как включить отображение ошибок вместо вывода сообщения об ошибке 500?

Arnas Damasickis avatar

Автор: Arnas Damasickis

Обновлено более недели назад

Как включить отображение ошибок и их логирование в панели управления hPanel?

В hPanel у Вас есть 2 варианта отслеживания ошибок PHP:

В обоих случаях, Вам нужно зайти в панель управления, затем открыть ХостингУправлятьКонфигурация PHP:

Здесь Вам понадобится вкладка Настройки PHP.

Обязательно сохраните изменения перед тем, как покинуть страницу. 😊

ПРИМЕЧАНИЕ:

Как включить отображение ошибок в WordPress?

Если Вы используете WordPress, в файловом менеджере откройте файл public_html/wp-config.php. Проверьте, есть ли в нём эта строка:

Если такая строка есть, измените «false» на «true». Затем добавьте строку:

Вот и всё, теперь на Вашем WordPress сайте будут отображаться ошибки PHP. 😊

Как включить отображение ошибок через .htaccess?

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

ВАЖНО: Обязательно создайте резервную копию Вашего файла .htaccess, прежде чем вносить какие-либо изменения, поскольку неправильные настройки могут сделать Ваш сайт недоступным.

ПРИМЕЧАНИЯ:

Понравилась статья? Поделить с друзьями:
  • Php выводить все ошибки и предупреждения
  • Php вывод ошибок только в файл
  • Php вывод ошибок ошибка 500
  • Php вывод ошибок в форме
  • Peugeot 407 как сбросить ошибки