Как исправить ошибку php 500

Страницу с кодом ответа 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, достаточно изучить их текст и принять меры, указанные в статье. Если вам не удается справиться с ней самостоятельно, обратитесь в службу поддержки.

Была ли эта инструкция полезной?

В php.ini включил display_errors и display_startup_errors, не помогло.

задан 8 июн 2012 в 8:31

ikirab1's user avatar

4

пробовали в начале скрипта прописать

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

ответ дан 25 июн 2015 в 3:32

des1roer's user avatar

des1roerdes1roer

2,6765 золотых знаков29 серебряных знаков68 бронзовых знаков

Отчего возникает ошибка 500 (Internal Server Error)?

Наиболее частой причиной ошибки 500 (Internal Server Error, внутренняя ошибка сервера) является неверный синтаксис файла .htaccess или наличие в нем неподдерживаемых директив. Чаще всего достаточно закомментировать директиву Options (для этого нужно поставить в начале строки решетку — #), и проблема исчезнет.

Ошибка 500 также может возникать вследствие неправильного обращения с CGI-скриптами:

CGI-скрипты должны иметь окончания строк в формате UNIX (n), а не в формате Windows (rn). Для этого их надо загружать на сервер по FTP в режиме ASCII.

CGI-скрипты и папки, в которых они находятся, должны быть доступны для записи только владельцу, то есть иметь права 0755 (drwxr-xr-x).

В результате работы CGI-скрипта сформированны неправильные HTTP-заголовки ответа. В этом случае для решения проблемы полезно обратиться к error_log (его можно найти в контрольной панели в разделе « Статистика / Лог-файлы / Лог ошибок»).

ответ дан 8 июн 2012 в 11:38

Eugene 1's user avatar

Eugene 1Eugene 1

2921 серебряный знак4 бронзовых знака

1

А что говорит error.log веб сервера. Один из вариантов, скрипт не выполняется из-за не правильно выставленных прав доступа.

ответ дан 8 июн 2012 в 11:35

gurzufnet's user avatar

gurzufnetgurzufnet

1,1346 серебряных знаков7 бронзовых знаков

1

Many website owners will have come across the “500 Internal Server Error” at some point in time. While this isn’t a very archaic error message, the more significant problem is that it may arise from many potential problems.

Thankfully, where PHP is concerned, the error is very specific – an inability to connect a request to the PHP script in question. For example, if a website visitor attempts to view a page and the connection times out, this error message will be displayed.

Resolving “500 Internal Server Error” While Running PHP

Although the root issue is known, what exactly is causing the connection to timeout can vary. Here are some of the more common methods to resolve this problem.

1. Reload or Refresh the Page

On occasion, the timeout may occur sporadically. Attempt to refresh the page a few times – if the web page can load at least once, an overloaded server likely causes the error.

Websites require resources to serve content to visitors. If your server lacks the resources to process the current volume of web traffic, you may see this error cropping up. To verify this, launch your SPanel dashboard and use the “Server Status” link to check resource usage trends.

How to Fix “500 Internal Server Error” While Running PHP

If your server is consuming many resources, provisioning for more will likely resolve your 500 Internal Server Error.

2. Check File Permissions

Another possibility is that the incorrect permissions have been set on the PHP file, causing the error. Verifying this will require you to connect to your server terminal (See “Connect to my server with SSH) and check log files.

Your log files will generally be located in “/usr/local/apache/logs/error_log”

If you note messages on “SoftException in Application,” the error message is likely caused by incorrect file permission settings. To resolve this, change the permissions for the related PHP file using the File Manager tool in SPanel.

3. Check .htaccess Code

In some cases, the “500 Internal Server Error” may be caused by specific instructions set in your .htaccess file. This file provides high-level web server configurations. Both you and some web applications may amend the file, potentially causing errors.

It is advisable to move all PHP-specific instructions out of the .htaccess file and into php.ini. The php.ini file is a custom configuration file that you can build for individual applications requiring PHP to run.

What’s your goal today?

1. Find the right Managed VPS solution

If you’re looking for industry-leading speed, ease of use and reliability Try ScalaHosting with an unconditional money-back guarantee.

2. Make your website lighting fast

We guarantee to make your WordPress site load in less than 2 seconds on a managed VPS with ScalaHosting or give your money back. Fill out the form, and we’ll be in touch.

3. Streamline your clients’ hosting experience

If you’re a web studio or development agency hosting more than 30 websites, schedule a call with Vlad, our co-founder and CTO, and see how we can deliver unmatched value to both your business and your clients.

Photo

Need a custom cluster or professional advice?

Book a meeting and get a free 30-minute consultation with Vlad, co-founder & CTO of Scala Hosting, who will help you select, design and build the right solution — from a single data center cluster to a multi-region & multi-datacenter high availability cluster with hundreds of servers.

Book a free consultation

4. Learn how to grow your website in 2023

An all-star team of SEO and web influencers are sharing their secret knowledge for the first time in years. Learn about the future of SEO, Web Design best practices and the secrets to getting the foundation for your website to thrive. Watch the exclusive webinar.

An Exclusive Insiders Look Behind The SEO and Web Development Curtain

Related articles

Working in the web hosting industry for over 13 years, Rado has inevitably got some insight into the industry. A digital marketer by education, Rado is always putting himself in the client’s shoes, trying to see what’s best for THEM first. A man of the fine detail, you can often find him spending 10+ minutes wondering over a missing comma or slightly skewed design.

This article describes ways to minimize the occurrence of «500 Internal Server Error» messages.

Table of Contents

  • Problem
  • Resolution
    • Set correct permissions
    • Check .htaccess directives

Problem

Visitors to your web site receive “500 Internal Server Error” messages when they access a page that uses PHP.

Resolution

Almost all of our servers run PHP as a CGI binary. One of the side effects of running PHP as a CGI binary is that internal server errors can occur if the permissions on files and directories are set incorrectly. Internal server errors can also occur if there are certain PHP directives defined in an .htaccess file.

If your web site is experiencing internal server errors, the first thing you should do is check the server logs. The server logs provide valuable information about which files are causing the errors, and potential causes. If you have a shared hosting account, you can view your web site’s error logs in cPanel. If you have a VPS or dedicated server, you can view your web site’s log files directly at the following paths:

  • /usr/local/apache/logs/error_log
  • /usr/local/apache/logs/suphp_log
Set correct permissions

If permission settings are causing internal server errors, you may see entries in the server logs similar to any of the following lines:

SoftException in Application.cpp:357: UID of script "/home/username/public_html/.htaccess" is smaller than min_uid

SoftException in Application.cpp:146: Mismatch between target UID (511) and UID (510) of file "/home/username/public_html/index.php"

SoftException in Application.cpp:256: File "/home/username/public_html/index.php" is writeable by others

These errors are all caused by permission issues. The first two lines indicate that the file’s owner or group is set incorrectly. For example, if the owner of a PHP file is the nobody or root account instead of your user account, visitors receive an internal server error when they try to view the page. If you have a shared hosting account, our Guru Crew can change the owners and groups for your files. If you need further assistance, please open a support ticket with our Guru Crew on the Customer Portal at https://my.a2hosting.com.

The third line indicates that file permissions for the index.php file are too permissive. For example, if your web site has a directory or file whose permissions are set to 777 (full permissions), anyone can read, write, or execute it. Additionally, visitors receive an internal server error when they try to view the page. To resolve this problem, change the permissions to 755 for directories and 644 for files. For example, to set the correct permissions for all directories and files in the public_html directory, type the following commands:

cd public_html
find . -type d -exec chmod 755 {} ;
find . -type f -exec chmod 644 {} ;

Do not change permissions on the public_html directory itself! Doing so may make your web site inaccessible.

Check .htaccess directives

Servers that run PHP as a CGI binary cannot use the php_flag or php_value directives in an .htaccess file. If directives in an .htaccess file are causing internal server errors, you will see entries in the server logs similar to the following line:

/home/username/public_html/.htaccess: Invalid command 'php_flag', perhaps misspelled or defined by a module not included in the server configuration

To resolve this problem, you must place any PHP directives into a custom php.ini file on your account, and remove or comment out any PHP directives in the .htaccess file. For information about how to set up a custom php.ini file, please see this article.

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

Понравилась статья? Поделить с друзьями:
  • Как исправить ошибку pdf файла
  • Как исправить ошибку pci контроллер simple communications
  • Как исправить ошибку page loading error
  • Как исправить ошибку page fault in nonpaged area
  • Как исправить ошибку p 0000065432