Cgi error php server

How to fix ‘500 Internal Server Error’ while running PHP This article describes ways to minimize the occurrence of «500 Internal Server Error» messages. 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 […]

Содержание

  1. How to fix ‘500 Internal Server Error’ while running PHP
  2. Problem
  3. Resolution
  4. Ошибка 500 Internal Server Error: что это и как её исправить
  5. Ошибка 500 Internal Server Error — диагностика
  6. Ошибка 500 Internal Server Error — устранение на популярных платформах
  7. Ошибка 500 Internal Server Error — устранение на стороне серверных скриптов
  8. Попросите помощи у системного администратора
  9. Ошибку 500 Internal Server Error довольно легко устранить
  10. Ошибка 500 — Internal Server Error
  11. Неверный синтаксис файла .htaccess
  12. Неправильное обращение с CGI-скриптами
  13. Медленная работа скрипта
  14. Неверные права на папки или файлы
  15. Несовместимость версий PHP
  16. Несовместимость расширений PHP
  17. Перенос строки не совместим с unix-форматом
  18. Установка плагина, шаблона или других дополнений
  19. [SOLUTIONS] 500 Internal Server Error PHP
  20. HOW TO FIX THE 500 INTERNAL SERVER ERROR
  21. CHECK YOUR SERVER ERROR LOGS
  22. ERROR WITH AN .HTACCESS FILE
  23. SYNTAX OR CODING ERRORS IN YOUR CGI/PERL SCRIPT
  24. CGI Script Guidelines
  25. Troubleshoot as a 504 Gateway Timeout error instead.
  26. Delete your browser’s cookies
  27. How To Fix the 500 Internal Server Error PrestaShop
  28. How To Fix the 500 Internal Server Error WordPress
  29. Checking for Corrupt .htaccess File
  30. Increasing the PHP Memory Limit
  31. How To Fix the 500 Internal Server Error Codeigniter

How to fix ‘500 Internal Server Error’ while running PHP

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

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:

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:

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:

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:

Источник

Ошибка 500 Internal Server Error: что это и как её исправить

Разработчики и люди, профессионально работающие с веб-приложениями, боятся 500 Internal Server Error . Оптимальный способ её устранения зависит от сервера и того, что на нём запущено. В данной статье приводятся советы по диагностике и исправлению ошибки 500 .

Ошибка 500 Internal Server Error — диагностика

Важно помнить, что эта ошибка происходит на стороне сервера. Это значит, что HTML-код , выполняемый на стороне клиента, а также JavaScript или любые другие запущенные в браузере объекты, не могут быть причиной, по которой возникает ошибка 500 Internal Server Error . Само название ( Internal Server Error – ‘внутренняя ошибка сервера’ ) говорит о том, что ошибка происходит на сервере.

Ошибка 500 Internal Server Error — устранение на популярных платформах

Многие пользователи устанавливают на свой сервер популярные CMS-системы , такие как WordPress , Joomla , Drupal и они не должны вызывать ошибку 500 , если всё настроено правильно. Однако она всё равно всплывает – из-за несовместимости версий, некачественных установок или сбоя прав доступа на сервере.

Вот некоторые распространённые проблемы, которые могут вызывать подобную ошибку в часто используемых CMS :

  • Если вы только что обновили движок до новой версии, вероятно, обновление прошло с ошибками и необходимо провести его повторно. Скорее всего, на сайте разработчика есть инструкции, как это правильно сделать.
  • Если вы только что активировали новый плагин или новую тему, стоит попробовать отменить эти изменения. Даже профессионально написанные плагины могут конфликтовать с другими и вызывать 500 Internal Server Error nginx
  • Если вы обновляли CMS , старые плагины и темы могут быть с ней несовместимы. Единственное, что можно сделать в таком случае — отключать их по очереди, пока ошибка 500 не исчезнет.
  • Неправильно заданные права доступа на сервере или ошибки в файле .htaccess . Серверу не удаётся получить доступ к скриптам, файлам и другим ресурсам, поэтому он выдаёт ошибку.

Когда причиной, по которой возникает ошибка 500 Internal Server Error являются скрипты и плагины, лучше всего искать ответы на сайтах их разработчиков.

Ошибка 500 Internal Server Error — устранение на стороне серверных скриптов

Другой причиной по которой может возникнуть ошибка 500 Internal Server Error может стать разработка и тестирование собственных скриптов.

Чтобы справиться с такой ошибкой, попробуйте следующие решения :

  • Настройка прав на сервере : часто неверная настройка прав доступа к файлу или папке приводит к тому, что сервером выдаётся ошибка 500 Internal Server Error . Из-за того, что ему не удаётся запустить скрипт. Выясните, какие права должны быть настроены, и выставьте их соответствующим образом.
  • Превышено время ожидания : возможно, истекло время ожидания ответа от PHP или другого серверного скрипта. Это происходит из-за того, что недоступен определённый ресурс или коде была допущена ошибка, запускающая бесконечный цикл.
  • Превышено время ожидания соединения с сервером: если сервер был занят, перезагружался или потерял соединение, скрипт может выдать ошибку 500 Internal Server Error . Возможно, в следующий раз ошибки не будет. Но если ошибка появляется при тестировании, велика вероятность того, что она встретится и пользователям.
  • Ошибки в файле .htaccess: в некоторых случаях ошибку 500 может вызывать код, прописанный в файле .htaccess .
  • Ошибки в скрипте: если ошибку выдаёт скрипт, можете запросить у него подробную информацию об ошибке. К примеру, в PHP можно включить вывод ошибок на экран или в лог-файл, добавив директиву display_errors . По умолчанию среда выполнения может скрывать ошибки, но это не очень удобно для отладки программы.

Попросите помощи у системного администратора

В некоторых случаях у разработчиков нет полного контроля над сервером.

Если скрипт запускается на сервере сторонней организации, она может помочь вам в следующем :

  • Предоставить документацию о своём сервере и возможных причинах ошибки 500 . В зависимости от используемой операционной системы и настройки оборудования, данная ошибка может возникать по разным причинам.
  • Попросите службу поддержки хостинга посмотреть лог-файлы с ошибками — системный администратор сможет определить, был ли сервер во время возникновения ошибки загружен или вовсе « упал ».

Ошибку 500 Internal Server Error довольно легко устранить

Ошибка 500 Internal Server Error — как исправить ? В большинстве случаев причины возникновения ошибки 500 легко исправляются. Проблема заключается в том, что без конкретной информации определение причины возникновения сбоя усложняется. Легче всего справиться с ошибкой, когда разработчик выяснит, что изменилось перед возникновением ошибки.

Не забывайте, что произошедшие изменения могли быть осуществлены и другими людьми — например, администратором сервера. Если же ничего не менялось, вероятно, сам сервер стал причиной возникновения ошибки из-за несовместимости программного обеспечения или проблем с производительностью.

Вадим Дворников автор-переводчик статьи « 500 Internal Server Error: What It Is And How To Fix It »

Источник

Ошибка 500 — Internal Server Error

500 Internal Server Error — это любая внутренняя ошибка сервера, которая не описана другими ошибками этого же класса.

Рассмотрим причины, которые могут привести к ошибке 500:

Неверный синтаксис файла .htaccess

Наиболее частой причиной ошибки 500 (Internal Server Error, внутренняя ошибка сервера) является неверный синтаксис файла .htaccess или наличие в нем неподдерживаемых директив.

Вы можете открыть файл .htaccess текстовым редактором и найти строки, в начале которых используются указанные конструкции. Найденные строки можно удалить или добавить в начале строки символ — # 1) . Файл .htaccess может находиться в корневом каталоге вашего сайта — на том же уровне, что и файлы index.php или index.html или robots.txt.

Неправильное обращение с CGI-скриптами

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

Медленная работа скрипта

Медленная работа скрипта. Например, есть ограничения от веб-сервера: если скрипт не активен в течение 60 секунд или зависает, то он завершается под видом ошибки 500.

Обычно достаточно поменять тарифный план на тариф с большим объемом PHP памяти.

Неверные права на папки или файлы

Убедитесь, что Вы нигде не выставили права /chmod 777 — ни на файлы, ни на папки.

В целях безопасности на наших серверах нельзя использовать данные права. Выставьте для папок 755, для файлов 644. Уверяем Вас, скрипты будут работать прекрасно с указанными правами, даже если в требованиях к скрипту есть установка прав 777.

Несовместимость версий PHP

Несовместимость расширений PHP

В php.ini включены не совместимые друг с другом расширения php. Например, одновременное включение eaccelerator и APC, либо eaccelerator и XCache почти наверняка будет приводить к ошибке Segmentation Fault и, как следствие, к ошибке 500 Internal Server Error на сайте.

Перенос строки не совместим с unix-форматом

Если Вы редактировали какие либо файлы сайта в ОС Windows, то при сохранении в файл могли добавиться не совместимые с unix-форматом символы переноса строки.

Для корректной работы необходимо использовать совместимые с unix-форматом переносы строк. Например, в Notepad++ этот параметр можно настроить в меню «Правка» → «Формат конца строк» → «Преобразовать в UNIX-формат».

Установка плагина, шаблона или других дополнений

Если Вы заметили, что после каких либо манипуляция с установкой дополнений на сайт 2) выскочила ошибка 500, то зачастую это можно исправить, удалить или отключить изменение.

Обычно это делается через панель администратора или по FTP соединению.

Если Вы все проверили, но не смогли найти ошибку, то создайте заявку в нашу службу поддержки, которая обязательно Вам поможет!

Источник

[SOLUTIONS] 500 Internal Server Error PHP

500 Internal Server Error is one of the common PHP errors that can put a PHP developer in panic mode. This article provides information on the most common causes. Why it become common PHP errors ? because you will found this error in WordPress, Prestashop, Codeigniter, Java, ASP.NET or whatever.

500 Internal Server Error is not a client side problem. It’s up to the sysadmin of the Web server site to locate and analyse the logs which should give further information about the error. Based on Wikipedia, 500 Internal Server Error is A generic error message, given when an unexpected condition was encountered and no more specific message is suitable.

Here are several common ways that you might see the HTTP 500 error:

  • “500 Internal Server Error”
  • “HTTP 500 – Internal Server Error”
  • “Temporary Error (500)”
  • “Internal Server Error”
  • “HTTP 500 Internal Error”
  • “500 Error”
  • “HTTP Error 500”
  • “500. That’s an error”

HOW TO FIX THE 500 INTERNAL SERVER ERROR

CHECK YOUR SERVER ERROR LOGS

With any error message, particularly one as broad as the 500 Internal Server Error, you will first want to check any Apache and PHP error logs for your server. These logs can provide valuable context related to any code failures or other potential causes of a site failure.

ERROR WITH AN .HTACCESS FILE

If you are using a .htaccess on your site, it may be interfering with the web page you are trying to load into your browser. Please double check the .htaccess configuration. Any syntax errors will cause a 500 Internal Server Error message to be displayed instead of your website.

To confirm whether a misconfiguration .htaccess is the cause of the 500 Internal Server error, either remove or rename the .htaccess file temporarily and then try to reload the page.

If your PHP script makes external network connections, the connections may time out. If too many connections are attempted and time out, this will cause a “500 Internal Server Error.” To prevent these time outs and errors, you’ll want to make sure that PHP scripts be coded with some timeout rules. Typically, however, catching a timeout error when connecting to a database or externally to remote resources (example: RSS feeds) are difficult. They, in effect, freeze the script from continuing to run.

Removing any external connections can increase both the performance of your website and decrease the chances of you receiving a “500 Internal Server Error.”

SYNTAX OR CODING ERRORS IN YOUR CGI/PERL SCRIPT

If it is a web page ending in .cgi or .pl that is producing the error, check your script for errors.

CGI Script Guidelines

When editing your CGI script, use a plain text editor – a program that saves the file as a ‘text file’ type. DO NOT use Wordpad that comes with Microsoft Windows because it doesn’t save files in pure ASCII text format. Use Notepad instead to edit files.
Upload your CGI scripts in ASCII mode into the cgi-bin directory.
Set the file permissions on the CGI script file and directories to be chmod 755. If you use an FTP program to transfer files, right-click on the file and select change file attributes.
Double-check that the Perl modules you require for your script is supported.

Troubleshoot as a 504 Gateway Timeout error instead.

It’s not very common, but some servers produce a 500 Internal Server Error when in reality a more appropriate message based on the cause of the problem is 504 Gateway Timeout.

Delete your browser’s cookies

Some 500 Internal Server Error issues can be corrected by deleting the cookies associated with the site you’re getting the error on. After removing the cookie(s), restart the browser and try again.

How To Fix the 500 Internal Server Error PrestaShop

There are two ways to turn on Error Reporting in PrestaShop depending on what version you have.

For PrestaShop v1.4 through v1.5.2

  1. Open config/config.inc.php
  2. On or around line 29 you will find this line
  3. Change that line to read

For PrestaShop v1.5.3+

  1. Open config/defines.inc.php
  2. On or around line 28 you will find this line
  3. Change that line to read

Once you enable error reporting through your FTP or CPanel, you can navigate back to your PrestaShop’s front or back office and reproduce the error or issue you are having. For example, if you are not able to access your website because of the 500 error, you will need to turn on error reporting and refresh the page(s) that had the error. There will be additional information that you can use to investigate the problem.

How To Fix the 500 Internal Server Error WordPress

Checking for Corrupt .htaccess File

The first thing you should do when troubleshooting the internal server error in WordPress is check for the corrupted .htaccess file. You can do so by renaming your main .htaccess file to something like .htaccess_old. To rename the .htaccess file, you will need to login to your site using the FTP. Once you are in, the .htaccess file will be located in the same directory where you will see folders like wp-content, wp-admin, and wp-includes.

Once you have renamed the .htaccess file, try loading your site to see if this solved the problem. If it did, then give yourself a pat on the back because you fixed the internal server error. Before you move on with other things, make sure that you go to Settings » Permalinks and click the save button. This will generate a new .htaccess file for you with proper rewrite rules to ensure that your post pages do not return a 404.

If checking for the corrupt .htaccess file solution did not work for you, then you need to continue reading this article.

Increasing the PHP Memory Limit

Sometimes this error can happen if you are exhausting your PHP memory limit. Use our tutorial on how to increase PHP memory limit in WordPress to fix that.

If you are seeing the internal server error only when you try to login to your WordPress admin or uploading an image in your wp-admin, then you should increase the memory limit by following these steps:

  1. Create a blank text file called php.ini
  2. Paste this code in there: memory=64MB
  3. Save the file
  4. Upload it into your /wp-admin/ folder using FTP

Several users have said that doing the above fixed the admin side problem for them.

If increasing the memory limit fix the problem for you, then you have fixed the problem temporarily. The reason why we say this is because there has to be something that is exhausting your memory limit. This could be a poorly coded plugin or even a theme function. We strongly recommend that you ask your WordPress web hosting company to look into the server logs to help you find the exact diagnostics.

If increasing the PHP memory limit did not fix the issue for you, then you are in for some hard-core trouble shooting.

How To Fix the 500 Internal Server Error Codeigniter

Check your error logs, sometimes the problem is with file permission, so make sure your file permission is 0755.

Источник

I am trying to run PHP via FastCGI on a Windows 2008 server.

I followed this installation doc http://learn.iis.net/page.aspx/246/using-fastcgi-to-host-php-applications-on-iis7/ and have checked I completed the steps correclty numerous times.

However when I try to execute a php page i am presented with the following error:

HTTP Error 500.0 — Internal Server Error
C:PHPphp-cgi.exe — The FastCGI process exited unexpectedly

asked Apr 11, 2014 at 8:38

Hamamelis's user avatar

2

After much pain and suffering, turns out I needed to install the «Visual C++ Redistributable for Visual Studio 2012 Update 4 32-bit version», even on my 64-bit server.

answered Nov 4, 2015 at 22:06

Ben's user avatar

BenBen

8718 silver badges4 bronze badges

4

You might be using C:/[your-php-directory]/php.exe in Handler mapping of IIS just change it C:/[your-php-directory]/php-cgi.exe.

answered Jan 22, 2015 at 11:25

Akshay Khale's user avatar

Akshay KhaleAkshay Khale

7,9738 gold badges50 silver badges58 bronze badges

2

I tried opening php-cgi.exe directly and it gave me a more clear error message.

answered Sep 13, 2015 at 1:24

Andrew's user avatar

AndrewAndrew

1,53317 silver badges31 bronze badges

As the answer of ‘sepehr’ this issues are because of VC++ Redistributable suitable version for PHP are not installed or need to be reinstalled again.

I faced it before so i’ll explain my steps to fix it.

1- Each PHP version is built by a specific Visual C++ Redistributable version like (10, 11,12,14,..) what ever.
((How you know!! look.. ))

  • Check back enter link description here The PHP Site then at the left side of this page, look at «Which version do I choose?» then see what version of VC++ is fits your PHP version installed.

  • Now YOU HAVE TO Download both of VC++ 32 and 64. and if your PC has it already then Unistall them first. and then install what you downloaded recently bu
    (first 32 then 64).

— VC download links are exists on the mentioned PHP Site on the left side also.

I hope it helps you.

answered May 4, 2017 at 8:58

Mohamed Abulnasr's user avatar

if you have two application like (your app, phpmyadmin) just disable APC extension
Hope that fix that issue
it’s worked with me

answered Mar 23, 2015 at 10:16

Basel AlkKaddoumi's user avatar

For user using PHP 5.6.x follow this link and install the x86 version.

answered Nov 18, 2016 at 19:11

Williem's user avatar

WilliemWilliem

1,1211 gold badge11 silver badges19 bronze badges

I have installed the latest version of Visual C++ Redistributable from this link for php 8.0.0 x86:

and my problem was solved.

answered Oct 10, 2021 at 6:16

rezaSefiddashti's user avatar

In my case the problem was coming through the application pool. Try to change your application pool ASP.NET v4.0.

answered Aug 25, 2014 at 10:45

Akshay Jindal's user avatar

In my case I had wrong constellation of configurations:

  • error reporting disabled
  • typo error in the configuration

After enabling the error_reporting it was clear the session_path was pointed to a wrong folder.

«Sad but true»

answered Oct 9, 2016 at 15:02

Stefan Michev's user avatar

Stefan MichevStefan Michev

4,6563 gold badges34 silver badges30 bronze badges

I was getting this same error installing PHP 7 on Windows Server 2008 R2. I resolved this by installing the Visual C++ Redistributable for Visual Studio 2015.

answered Feb 2, 2017 at 20:55

carltonstith's user avatar

1

For Issue C:PHPphp-cgi.exe — The FastCGI process exited unexpectedly.

I resolved this by installing the Visual C++ Redistributable for Visual Studio 2015.(Microsoft Visual C++ 2015 Redistributable Update 3) and Visual C++ Redistributable for Visual Studio 2012 Update 4 in 32 and 64bit versions. and also make sure in php.info file cgi.fix_pathinfo=0 enabled.

answered Jan 26, 2018 at 6:24

RaghuPathi Balasani's user avatar

I got this error too after I changing PHP version in windows.
I have PHP Manager plug in of IIS installed, it show the PHP is not enabled, then I fix this issue after doing «Register new PHP version»
enter image description here

answered Jul 20, 2021 at 2:51

Nolan Shang's user avatar

Nolan ShangNolan Shang

2,2821 gold badge14 silver badges10 bronze badges

I struggled for hours with that problem, and no solution worked for me. May seems obvious or very foolish, but my error was in PHP 5.6 version. I was using PHP 5.6 from XAMPP, but if you download PHP on IIS with Web PI (Microsoft Web Platform Installer) it’s more suitable for IIS instead XAMPP version.

More Info:

How to Host PHP on Windows With IIS

answered Sep 22, 2021 at 13:37

Ulises Vargas De Sousa's user avatar

Running php-cgi.exe from the command line gave a message like the vcrt dll is a lower version than what is linked in php.
Using Visual C++ redistributable package 64 bit 14.29 solved the above problem for me.

answered Nov 26, 2022 at 16:14

Polymath's user avatar

PolymathPolymath

4815 silver badges10 bronze badges

In my previous articles on PHP error handling, I explain the process whereby PHP error handling may be achieved using htaccess. Handling (logging, reporting) PHP errors via htaccess requires the following:

  • Access/editing privileges for htaccess files
  • A server running PHP via Apache, not CGI (e.g., phpSuExec)1
  • Ability to edit/change permissions for files on your server

If you are having trouble handling PHP errors using htaccess, these three items are the first things to check. If it turns out that you are unable to use htaccess to work with PHP errors, don’t despair — this article explains how to achieve the same goals using local php.ini files. To implement this strategy, the following is required:

  • Ability to create/edit a php.ini file in your public_html directory
  • A server running PHP via CGI (e.g., phpSuExec), not Apache2
  • Ability to edit/change permissions for files on your server
  • Access/editing privileges for htaccess files (not required)

Assuming satisfaction of the preceding requirements, the remainder of this tutorial explains how to enable global (sitewide) PHP error handling using a custom php.ini file. After explaining the implementation process for production environments, we will explore several useful functional customizations for both production and development servers3. Excited? Great, let’s begin..

Step 1: Add custom php.ini file to site root directory

Using a text editor, create a file named “php.ini” and add the following PHP directives4:

;;; php error handling for production servers
display_startup_errors = off
display_errors = off
html_errors = off
log_errors = on
docref_root = 0
docref_ext = 0
error_log = /var/log/php/errors/php_error.log

Here, we are disabling all public error displays and enabling private error logging in the specified file. After editing the path and file name of the error log in the last line, save the file and upload it to the root directory of your domain. Generally, this directory is named “public_html”, but it may be different on your server. Then, create the specified log file and ensure that it is writable (via 755 or 777) by the server.

Step 2: Enable subdirectory inheritance of custom settings

At this point, error logging should be working, but only for the same directory in which you have placed the php.ini file. Unfortunately, by default, locally specified php.ini directives only affect the directory in which they are located — they are not inherited by subdirectories as they are for htaccess directives. Thus, each directory for which you would like to log errors requires its own copy of the php.ini file. Fortunately, if you are able to access and edit your site’s root htaccess file, there is an easy way to enable subdirectory inheritance of your custom php.ini settings. Simply add the following code to your site’s root htaccess file:

# enable subdirectory inheritance of custom php settings
suPHP_ConfigPath /home/path/public_html

This trick takes advantage of htaccess’ inheritance properties by using them to “point” from each subdirectory to the custom php.ini file in the root (e.g., public_html) directory. Note that you may override the root php.ini directives by placing alternate php.ini files in the target subdirectory.

Step 3: Secure your custom php.ini and log files

Once everything is working, it is important to protect your domain by securing your newly created files. In addition to setting permissions to 600 for your custom php.ini file(s), you may also want to add the following directives to your root htaccess file:

# deny access to php.ini
<Files php.ini>
 order allow,deny
 deny from all
 satisfy all
</Files>

# deny access to php error log
<Files php_error.log>
 order allow,deny
 deny from all
 satisfy all
</Files>

And that’s it — PHP error logging should now be securely enabled on your domain. Now let’s explore some useful functional customizations for both production and development servers..

Controlling the level of PHP error reporting

Using your custom php.ini file, it is possible to set the level of error reporting to suit your particular needs. The general format for controlling the level of PHP errors is as follows:

;;; general directive for setting php error level
error_reporting = integer

There are several common values used for “integer”, including:

  • Complete error reporting — for complete PHP error logging, use an error-reporting integer value of “8191”, which will enable logging of everything except run-time notices5.
  • Zend error reporting — to record both fatal and non-fatal compile-time warnings generated by the Zend scripting engine, use an error-reporting integer value of “128”.
  • Basic error reporting — to record run-time notices, compile-time parse errors, as well as run-time errors and warnings, use “8” for the error-reporting integer value.
  • Minimal error reporting — to record only fatal run-time errors, use an error-reporting integer value of “1”, which will enable logging of unrecoverable errors.

Of course, there are many more error-reporting values to use, depending on your particular error-logging needs. For more information on logging PHP errors, refer to the Error Handling and Logging Functions page at php.net.

Setting the maximum file size for your error strings

Using your custom php.ini file, you may specify a maximum size for your PHP errors. This controls the size of each logged error, not the overall file size. Here is the general syntax:

;;; general directive for setting max error size
log_errors_max_len = integer

Here, “integer” represents the maximum size of each recorded error string as measured in bytes. The default value is “1024” (i.e., 1 kilobyte). To unleash your logging powers to their fullest extent, you may use a zero value, “0”, to indicate “no maximum” and thus remove all limits. Note that this value is also applied to displayed errors when they are enabled (e.g., during development).

Disable logging of repeated errors

If you remember the last time you examined a healthy (or sick, depending on your point of view) PHP error log, you may recall countless entries of nearly identical errors, where the only difference for each line is the timestamp of the event. If you would like to disable this redundancy, throw down the following code in your custom php.ini file:

;;; disable repeated error logging
ignore_repeated_errors = true
ignore_repeated_source = true

With these lines in place, repeated errors will not be logged, even if they are from different sources or locations. If you only want to disable repeat errors from the same source or file, simply comment out or delete the last line [note: comments must begin with a semicolon ( ; ) in php.ini files]. Conversely, to ensure that your log file includes all repeat errors, change both of the true values to false.

Putting it all together — Production Environment

Having discussed a few of the useful ways to customize our PHP error-logging experience, let’s wrap it all up with a solid, php.ini-based error-handling strategy for generalized production environments. Here is the code for your custom php.ini file:

;;; php error handling for production servers
display_startup_errors = false
display_errors = false
html_errors = false
log_errors = true
ignore_repeated_errors = false
ignore_repeated_source = false
report_memleaks = true
track_errors = true
docref_root = 0
docref_ext = 0
error_log = /var/log/php/errors/php_error.log
error_reporting = 999999999
log_errors_max_len = 0

Or, if you prefer, an explanatory version of the same code, using comments to explain each line:

;;; php error handling for production servers

; disable display of startup errors
display_startup_errors = false

; disable display of all other errors
display_errors = false

; disable html markup of errors
html_errors = false

; enable logging of errors
log_errors = true

; disable ignoring of repeat errors
ignore_repeated_errors = false

; disable ignoring of unique source errors
ignore_repeated_source = false

; enable logging of php memory leaks
report_memleaks = true

; preserve most recent error via php_errormsg
track_errors = true

; disable formatting of error reference links
docref_root = 0

; disable formatting of error reference links
docref_ext = 0

; specify path to php error log
error_log = /var/log/php/errors/php_error.log

; specify recording of all php errors
error_reporting = 999999999

; disable max error string length
log_errors_max_len = 0

This PHP error-handling strategy is ideal for a generalized production environment. In a nutshell, this code secures your server by disabling public display of error messages, yet also enables complete error transparency for the administrator via private error log. Of course, you may wish to customize this code to suit your specific needs. As always, please share your thoughts, ideas, tips and tricks with our fellow readers. Now, let’s take a look at a generalized error-handling strategy for development environments..

Putting it all together — Development Environment

During project development, when public access to your project is unavailable, you may find it beneficial to catch PHP errors in real time, where moment-by-moment circumstances continue to evolve. Here is a generalized, php.ini-based PHP error-handling strategy for development environments. Place this code in your custom php.ini file:

;;; php error handling for production servers
display_startup_errors = true
display_errors = true
html_errors = true
log_errors = true
ignore_repeated_errors = false
ignore_repeated_source = false
report_memleaks = true
track_errors = true
docref_root = 0
docref_ext = 0
error_log = /var/log/php/errors/php_error.log
error_reporting = 999999999
log_errors_max_len = 0

For this code, we will forego the line-by-line explanations, as they may be extrapolated from the previous section. This PHP error-handling strategy is ideal for a generalized development environment. In a nutshell, this code enables real-time error-handling via public display of error messages, while also enabling complete error transparency for the administrator via private error log. Of course, you may wish to customize this code to suit your specific needs. As always, please share your thoughts, ideas, tips and tricks with our fellow readers.

Whew! That about does it for this article.. — see you next time!

Footnotes

  • 1 To determine if your server is running PHP via phpSuExec (i.e., CGI) instead of Apache, upload a phpinfo() file and check the “Server API” near the top of the file. If it says “Apache”, PHP is running on Apache; if it says “CGI”, PHP is running via phpSuExec.
  • 2 This is important because it is impossible to manipulate php.ini directives via htaccess while running PHP on phpSuExec.
  • 3 For more information, check out the manual on Error Handling and Logging Functions at php.net
  • 4 Many thanks to Jeff N. at A Small Orange for helping with the information provided in this article  :)
  • 5 Due to the bitwise nature of the various error-reporting values, the value for logging all errors continues to increase. For example, in PHP 5.2.x, its value is 6143, and before that, its value was 2047. Thus, to ensure comprehensive error logging well into the future, it is advisable to set a very large value for error_reporting, such as 2147483647.

Jeff Starr

About the Author

Jeff Starr = Creative thinker. Passionate about free and open Web.

Понравилась статья? Поделить с друзьями:
  • Cfosspeed fatal error
  • Cf80 ошибка bmw x1
  • Cf77 ошибка бмв
  • Cf60 ошибка bmw e70
  • Cf5e ошибка bmw