You may use the following function to send a status change:
function header_status($statusCode) {
static $status_codes = null;
if ($status_codes === null) {
$status_codes = array (
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended'
);
}
if ($status_codes[$statusCode] !== null) {
$status_string = $statusCode . ' ' . $status_codes[$statusCode];
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
}
}
You may use it as such:
<?php
header_status(500);
if (that_happened) {
die("that happened")
}
if (something_else_happened) {
die("something else happened")
}
update_database();
header_status(200);
The 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.
Ending 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
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
You may use the following function to send a status change:
function header_status($statusCode) {
static $status_codes = null;
if ($status_codes === null) {
$status_codes = array (
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
509 => 'Bandwidth Limit Exceeded',
510 => 'Not Extended'
);
}
if ($status_codes[$statusCode] !== null) {
$status_string = $statusCode . ' ' . $status_codes[$statusCode];
header($_SERVER['SERVER_PROTOCOL'] . ' ' . $status_string, true, $statusCode);
}
}
You may use it as such:
<?php
header_status(500);
if (that_happened) {
die("that happened")
}
if (something_else_happened) {
die("something else happened")
}
update_database();
header_status(200);
День добрый.
После вставки на страницу сайта данного кода, страница перестала открываться и пишет HTTP ERROR 500.
Умельцы, гляньте, пожалуйста. Я не в состоянии найти ошибку самостоятельно в связи с тем, что в PHP всего 3-тий день
<div class="panel panel-default">
<?php
include("db_connect.php");
$steamIds = [];
$usersData = [];
$query = "SELECT * FROM users_profiles ORDER BY `id` DESC limit 15";
$result = mysqli_query($query) or die("Request failed");
while ($row = mysqli_fetch_assoc($result)) {
$usersData[$row['steam_id']] = $row;
$steamIds = $row['steam_id']
}
$url = "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=" . $steamauth['apikey'] . "&steamids=" , join(',', $steamIds);
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$uuser);
$result=curl_exec($ch);
curl_close($ch);
$steamData = json_decode($result, true);
foreach($steamData['response']['players'] as &$player) {
$usersData[$player['steamid']]['steam_avatar'] = $player['avatarfull'];
$usersData[$player['steamid']]['steam_name'] = $player['personaname'];
}
$chunked = array_chunk($usersData, 3);
?>
<table class="table table-striped table-responsive table-bordered">
<tbody>
<?php foreach($chunked as &$chunked_row): ?>
<tr>
<?php foreach($chunked_row as &$chunked_cell): ?>
<td>
<center>
<img src="<?= htmlspecialchars($chunked_cell['steam_avatar']); ?>" width="50px" height="50px"/>
<?= htmlspecialchars($chunked_cell['steam_avatar']); ?>
</center>
</td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
Страницу с кодом ответа 500 веб-сервер возвращает, когда не может обработать запрос из-за ошибок в файлах сайта.
Внешний вид ошибки 500 зависит от того, чем она вызвана. При неполадках в скриптах сайта отобразится пустая страница, сообщение HTTP ERROR 500 или текст обработчика PHP.
Если проблема в файле .htaccess — сообщение Internal Server Error.
Часто ошибку 500 можно легко устранить даже не имея знаний в области веб-разработки. О том, как это сделать, расскажем далее.
Ошибки в файле .htaccess
Сообщение Internal Server Error выводится, когда в файле .htaccess есть ошибки. Переименуйте файл .htaccess и проверьте корректность работы сайта. Если он доступен, удалите правила, которые были добавлены последними, или восстановите старый файл из резервной копии.
Ошибки в скриптах сайта
Пустая страница — не всегда признак ошибки 500. Поэтому в первую очередь узнайте код ответа, с которым она открывается. Это можно сделать при помощи инструментов разработчика в браузерах.
Инструменты разработчика — функция для исследования работы сайта. Она позволяет узнать время ответа сервера, код ответа, посмотреть текст возникших ошибок и многое другое.
Нажмите сочетание клавиш Ctrl+Shift+I или используйте меню браузера:
- Mozilla Firefox — «Веб-разработка» → «Инструменты разработчика»;
- Google Chrome — «Дополнительные инструменты» → «Инструменты разработчика»;
- Opera — «Разработка» → «Инструменты разработчика».
Перейдите во вкладку «Сеть (Network)». На ошибку 500 указывает соответствующее число в колонке «Статус».
Статус пустой страницы может быть и 200 (Ok). В таком случае проверьте, есть ли содержимое в индексном файле сайта, очистите кеш вашей CMS. Если ранее сайт работал корректно, восстановите его из резервной копии.
Вывод ошибок на сайте
Вывод ошибок PHP на хостинге по умолчанию выключен. Чтобы увидеть их текст, добавьте в файл .htaccess правило: php_value display_errors 1
и обновите страницу сайта.
Если текст не отобразился, включите вывод ошибок через конфигурационный файл CMS. Он расположен в корневой директории сайта.
WordPress
Замените в файле wp-config.php строку define(‘WP_DEBUG’, false);
на define(‘WP_DEBUG’, true);
Joomla
Измените значение переменных debug и error_reporting в configuration.php на: public $debug = '1';
и public $error_reporting = 'maximum';
1С-Битрикс
В конфигурационном файле по пути ~/public_html/bitrix/php_interface/dbconn.php замените значение переменных DBDebug и DBDebugToFile на: $DBDebug = true;
и $DBDebugToFile = true;
Laravel
В файле .env измените APP_DEBUG=false
на APP_DEBUG=true
Алгоритм устранения ошибки можно найти в интернете, поместив ее текст в строку любой поисковой системы. Если с помощью найденной информации возобновить работу сайта не получится, восстановите его из резервной копии. Наши специалисты могут помочь с восстановлением. Для этого направьте обращение из раздела «Поддержка» Панели управления.
Журнал ошибок PHP
Иногда ошибка не выводится на странице или возникает периодически: ее тяжело отследить. Чтобы узнать текст таких ошибок, записывайте информацию о них в файл — журнал ошибок PHP. Подключите его, добавив в .htaccess строку: php_value error_log /home/username/domains/domain.ru/php_errors.log
и обновите страницу сайта.
Откройте создавшийся файл журнала с помощью Файлового менеджера в Панели управления. Чтобы просматривать возникающие ошибки в реальном времени, отметьте опцию «Включить автообновление».
Быстро возобновить работу сайта можно, восстановив его из резервной копии за дату, когда ошибок не было. Если восстановление нежелательно, обратитесь к разработчику.
Для устранения некоторых ошибок не требуется специальных знаний. Рассмотрим самые распространенные.
Нехватка оперативной памяти
Ошибка с текстом Allowed memory size возникает из-за нехватки оперативной памяти для выполнения скрипта: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 81 bytes) in /home/username/domains/domain.ru/public_html/somescript.php
Чтобы исправить ее, увеличьте лимит оперативной памяти, добавив в файл .htaccess директиву:
php_value memory_limit 512M
Вместо «512» укажите необходимый объем памяти. Максимальное значение ограничивается тарифом.
Текст Out of memory означает, что достигнут лимит оперативной памяти по тарифному плану:
PHP Fatal error: Out of memory (allocated 39059456) (tried to allocate 262144 bytes) in /home/username/domains/domain.ru/public_html/somescript.php
Оптимизируйте работу скриптов, чтобы они потребляли меньше памяти. Объемную загрузку или выгрузку данных производите частями. Если оптимизацию произвести невозможно, измените тариф на тот, по которому предоставляется достаточно памяти для комфортной работы сайта.
Ошибки в CMS
При обновлении CMS случаются синтаксические ошибки:
PHP Parse error: syntax error, unexpected '[', expecting ')' in /home/username/domains/domain.ru/public_html/wp-content/plugins/wordpress-23-related-posts-plugin/config.php on line 130
Это происходит из-за того, что новые функции CMS не поддерживают устаревшие версии PHP. Чтобы исправить ошибку, измените версию PHP для сайта на более современную в разделе «Сайты» → «Веб-серверы».
Если предыдущая рекомендация не помогла, обратите внимание на путь до неработающего скрипта: там может быть указан каталог плагина или темы. Чтобы исправить ошибку, отключите их. Для этого переименуйте папку, в которой они расположены. После устранения ошибки авторизуйтесь в административной части сайта и измените тему или переустановите плагин.
Чтобы исправить большинство ошибок PHP, достаточно изучить их текст и принять меры, указанные в статье. Если вам не удается справиться с ней самостоятельно, обратитесь в службу поддержки.
Была ли эта инструкция полезной?