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,6351 gold badge16 silver badges29 bronze badges

answered Apr 22, 2010 at 1:49

awgy's user avatar

awgyawgy

16.6k4 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

13.2k12 gold badges92 silver badges130 bronze badges

answered May 25, 2016 at 3:53

Aaron's user avatar

AaronAaron

5831 gold badge5 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,1105 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,5611 gold badge24 silver badges29 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

5284 silver badges10 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,4281 gold badge18 silver badges25 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,6351 gold badge16 silver badges29 bronze badges

answered Apr 22, 2010 at 1:49

awgy's user avatar

awgyawgy

16.6k4 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

13.2k12 gold badges92 silver badges130 bronze badges

answered May 25, 2016 at 3:53

Aaron's user avatar

AaronAaron

5831 gold badge5 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,1105 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,5611 gold badge24 silver badges29 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

5284 silver badges10 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,4281 gold badge18 silver badges25 bronze badges

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

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

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

  • Php отправить ошибку 500
  • Php ошибка 400
  • Php ошибка 2002
  • Php отследить ошибку
  • Php отправить код ошибки

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

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