Php вывод ошибок ошибка 500

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.

PHP fatal errors come back as status code 200 to the HTTP client. How can I make it return a status code 500 (Internal server error)?

pnuts's user avatar

pnuts

58.1k11 gold badges86 silver badges138 bronze badges

asked Oct 12, 2009 at 17:25

Mike's user avatar

3

header("HTTP/1.1 500 Internal Server Error");

answered Oct 12, 2009 at 17:28

C. K. Young's user avatar

C. K. YoungC. K. Young

219k45 gold badges381 silver badges435 bronze badges

3

This is exactly the problem I had yesterday and I found solution as follows:

1) first of all, you need to catch PHP fatal errors, which is error type E_ERROR. when this error occurs, script will be stored the error and terminate execution. you can get the stored error by calling function error_get_last().

2) before script terminated, a callback function register_shutdown_function() will always be called. so you need to register a error handler by this function to do what you want, in this case, return header 500 and a customized internal error page (optional).

function my_error_handler()
{
  $last_error = error_get_last();
  if ($last_error && $last_error['type']==E_ERROR)
      {
        header("HTTP/1.1 500 Internal Server Error");
        echo '...';//html for 500 page
      }
}
register_shutdown_function('my_error_handler');

Note: if you want to catch custom error type, which start with E_USER*, you can use function set_error_handler() to register error handler and trigger error by function trigger_error, however, this error handler can not handle E_ERROR error type. see explanation on php.net about error handler

Dmitry Pashkevich's user avatar

answered Jan 13, 2012 at 14:09

fuyi's user avatar

fuyifuyi

2,5334 gold badges22 silver badges46 bronze badges

2

Standard PHP configuration does return 500 when error occurs! Just make sure that your display_errors = off. You can simulate it with:

ini_set('display_errors', 0); 
noFunction();

On production display_errors directive is off by default.

answered Apr 5, 2016 at 13:27

lukyer's user avatar

lukyerlukyer

7,4553 gold badges37 silver badges31 bronze badges

2

I have used «set_exception_handler» to handle uncaught exceptions.

function handleException($ex) {
      error_log("Uncaught exception class=" . get_class($ex) . " message=" . $ex->getMessage() . " line=" . $ex->getLine());
      ob_end_clean(); # try to purge content sent so far
      header('HTTP/1.1 500 Internal Server Error');
      echo 'Internal error';
    }

set_exception_handler('handleException');

answered Sep 23, 2010 at 10:10

Matti Haavikko's user avatar

2

Since PHP >= 5.4

http_response_code(500);
echo json_encode( [ 'success' => false , 'message' => 'Crazy thing just happened!' ]);
exit();

Please set the httpCode before echo.

answered Jun 16, 2020 at 5:09

vanduc1102's user avatar

vanduc1102vanduc1102

5,6401 gold badge45 silver badges42 bronze badges

It is not possible to handle PHP E_ERROR in any way according to the PHP documentation:
http://www.php.net/manual/en/function.set-error-handler.php

Nor is is possible to handle «E_PARSE, E_CORE_ERROR, E_CORE_WARNING, E_COMPILE_ERROR, E_COMPILE_WARNING, and most of E_STRICT» according to that link.

You CAN provide a handler for the other error, warning, and notices including E_USER_ERROR, but that’s really not as useful as it sounds since this error only gets thrown intentionally by the programmer with trigger_error().

And of course you can catch any Exception (even the ones thrown by the native PHP functions).

I agree that this is a problem. Servers should NOT return 200 OK when application code crashes and burns.

answered Jan 24, 2010 at 2:41

Jonathan Hanson's user avatar

Jonathan HansonJonathan Hanson

4,6111 gold badge19 silver badges16 bronze badges

1

answered Oct 12, 2009 at 17:28

Xinus's user avatar

XinusXinus

29.4k30 gold badges118 silver badges165 bronze badges

1

You would have to catch the thrown error using try/catch and then use that catch block to send a header() with the 500 error.

try {
    ...badcode...
    throw new Exception('error');

} catch (Exception $e) {

    header("Status: 500 Server Error");
    var_dump($e->getMessage());
}

If the fatal exception is not surrounded by try {} catch blocks then you must register a global handler and use register_shutdown_function() to check for an error at script end.

answered Oct 12, 2009 at 17:30

Xeoncross's user avatar

XeoncrossXeoncross

55.3k79 gold badges260 silver badges363 bronze badges

5

Never forget to set header("HTTP/1.1 200 OK", true, 200); as the last line of any execution path:

//first things first:
header("HTTP/1.1 500 Internal Server Error", true, 500);


//Application code, includes, requires, etc. [...]


//somewhere something happens
//die();
throw new Exception("Uncaught exception!");


//last things last, only reached if code execution was not stopped by uncaught exception or some fatal error
header("HTTP/1.1 200 OK", true, 200);

In PHP 5.4 you can replace the header function above with the much better http_response_code(200) or http_response_code(500).

answered Aug 1, 2012 at 17:41

oxygen's user avatar

oxygenoxygen

5,8546 gold badges37 silver badges68 bronze badges

2

The hard thing when dealing with fatal errors (compile errors, for example a missing semicolon) is that the script won’t be executed, so it won’t help to set the status code in that script. However, when you include or require a script, the calling script will be executed, regardless of errors in the included script. With this, I come to this solution:

rock-solid-script.php:

// minimize changes to this script to keep it rock-solid
http_response_code(500); // PHP >= 5.4
require_once("script-i-want-to-guard-for-errors.php");

script-i-want-to-guard-for-errors.php:

// do all the processsing
// don't produce any output
// you might want to use output buffering

http_response_code(200); // PHP >= 5.4

// here you can produce the output

Direct your call to the rock-solid-script.php and you’re ready to go.

I would have liked it better to set the default status code to 500 in .htaccess. That seems more elegant to me but I can’t find a way to pull it off. I tried the RewriteRule R-flag, but this prevents execution of php altogether, so that’s no use.

answered Feb 22, 2013 at 17:50

Remco Nijhuis's user avatar

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 внутренних ошибок сервера. Конечно, раньше, когда он отображал ошибку, это были разные серверы. Теперь я на новом сервере (у меня есть полный корень, поэтому, если мне нужно настроить его где-нибудь в 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)

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

Понравилась статья? Поделить с друзьями:
  • Peugeot 407 как сбросить ошибки
  • Perfect world mobile ошибка сервера
  • Pantum p2500w внутренняя ошибка принтера 002
  • Pantum m6500 неизвестная ошибка 64
  • Panasonic nn cd997s ошибка h97