PHP Error Logging via .htaccess


  • Applies to: All Service Types
    • Difficulty: Medium
    • Time: 10 minutes
    • Tools needed:¬†SSH

Overview

The following article will demonstrate how to enable advanced PHP error logging functionality for a domain on a Linux server. This will work on any (mt) Media Temple hosting service.

PHP Error Logging

The web server access and error logs do not always provide sufficient information to determine the source a PHP error. Luckily, PHP provides excellent error reporting/handling options, you just have to enable them to take advantage.

Instructions

To log PHP errors for the "example.com" website, add the following lines to the .htaccess file in your "web root" folder:


# suppress PHP errors from displaying in the browser
php_flag display_startup_errors off
php_flag display_errors off
php_flag html_errors off

# log PHP errors to a file
php_flag log_errors on
php_value error_reporting 32767
php_value error_log "/path/to/file"

Notes

    • In the above code, the integer 32767 is used to denote the "E_ALL" level of error reporting in legacy PHP versions. Depending on the specific version of PHP you are running on that domain, the integer values may correspond differently to the error verbosity levels. 32767, however, should continue to function as "E_ALL" in newer versions of PHP.

    • Visit http://www.php.net/manual/en/errorfunc.constants.php for information on the different levels of error reporting available and their corresponding integer codes.

    • It is best to keep the log in a directory which is NOT web-accessible; some PHP errors may expose vulnerabilities or sensitive information that could be useful to a visitor with malicious intent.

    • Depending on the level of verbosity you have selected for your PHP error logging and the frequency of errors/warnings generated, the PHP error logging file could grow very large very quickly. Be sure to keep a close eye on the size of this file and to only have the error logging enabled if you are actively debugging potential site coding issues.

Using the Errors to Troubleshoot Code

You can access the log file wherever you configured it to be written. In the example above, the file can be accessed at /path/to/file. Each error will each be reported on a new line and each line will be timestamped. Here is an example error line:


[09-Dec-2012 18:58:57] PHP Fatal error:  Call to undefined function eccho() in /path/to/example.com/html/samplefile.php on line 2

From the above error sample, it is easy to see that the problem is that the "eccho" function does not exist. Since we know that "echo" is a function in PHP, it would be a safe bet that there was just a typo in the PHP code on line 2 of the "samplefile.php" file.

Relevant Links