Php error output to file

Запись ошибок выполнения PHP скриптов в файл

Все php ошибки нужно обязательно записывать в лог-файл и регулярно изучать его. Если этого не делать — есть шанс пропустить часть багов, которые появляются в процессе работы или тестирования и не выводятся на экран. По умолчанию, запись ошибок в файл отключена на многих конфигурациях (и это правильно!), но есть несколько способов это исправить:

Способ 1 — написать функцию перехвата ошибок и записи их в файл:

# В начале нашего скрипта пишем: set_error_handler('err_handler'); function err_handler($errno, $errmsg, $filename, $linenum) < $date = date('Y-m-d H:i:s (T)'); $f = fopen('errors.txt', 'a'); if (!empty($f)) < $filename =str_replace($_SERVER['DOCUMENT_ROOT'],'',$filename); $err = "$errmsg = $filename = $linenum\r\n"; fwrite($f, $err); fclose($f); >> 

Способ 2 — изменить php.ini:

log_errors = On error_log = /var/log/php_errors.log 

Способ 3 — добавить в .htaccess:

php_value log_errors "On" php_value error_log /var/log/php_errors.log 

Способ 4 — добавить в самое начало php скрипта:

ini_set('log_errors', 'On'); ini_set('error_log', '/var/log/php_errors.log');

Если создание сайтов было выполнено качественно, то и ошибок выводиться на экран не должно. Конечно, не всегда этого можно добиться по этому в идеале, перестраховаться и писать уведомления в файл. Крайне не рекомендуется использовать символ собаки @ для подавления ошибок т.к. в последствии можно пропустить очень важное уведомление.

Источник

Php error output to file

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?
Читайте также:  font-family

Источник

How to log PHP errors and warnings into a file

This class collects all the errors reported from a PHP script, classifies them as either general errors or fatal errors. After classification, it passes the error to the respective method which then calls the log function that writes them out.

Let’s define some constant variables here.

/** * if your error class file resides in a folder called classes and the index file is in the base folder use: * * define('ERR_HANDLER_PATH', substr(dirname(__file__), 0, strpos(dirname(__file__), 'classes') - 1) . '/'); // DO NOT change!! * * after using the above line comment or remove the fisrt line down here **/ define('ERR_HANDLER_PATH', dirname(__file__).'/'); // DO NOT change!! define('ERR_HANDLER_LOG_FOLDER', 'logs'); // Name of logs folder.. Create if it does not exist. define('ERR_HANDLER_ENABLED', 1); // Enable custom error handler? define('ERR_HANDLER_DISPLAY', 1); // Display a message on screen? define('ERR_APPEND_RAND_STRING', 0); // Adds random string to file name for security. Prevents someone attempting browser access. define('MASK_FILE_PATH', 0); // Hide file path if error occurs.. define('FILE_ERR_LOG_FILE', 'errors.log'); // File name of error log define('FILE_FATAL_ERR_LOG_FILE', 'fatal_errors.log'); // File name of fatal error log 

We create our class which has four functions and each function calls the log function when invoked:

  • generalErr — This function is invoked when a general error occurs.
  • mailErr — This function is invoked when an email error occurs.(if you have an email sending script)
  • fataErr — This function is invoked when a fatal error occurs and no further execution can happen.
  • log — calls the write function which then writes the error into a file.
class Errs  public function generalErr($error)  Errs::log($error, FILE_ERR_LOG_FILE); > public function mailErr($error)  Errs::log($error, FILE_ERR_LOG_FILE); > public function fatalErr($error)  Errs::log($error, FILE_FATAL_ERR_LOG_FILE); > public function log($error, $file)  if (is_dir(ERR_HANDLER_PATH . ERR_HANDLER_LOG_FOLDER))  write(ERR_HANDLER_PATH . ERR_HANDLER_LOG_FOLDER . '/' . Errs::raStr() . $file, trim($error) . linending() . '***** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *****' . linending()); > > public function raStr()  return (ERR_APPEND_RAND_STRING ? substr(md5(uniqid(rand(),1)), 3, 30) . '-' : ''); > > // Initiate the class.. $DDEH = new Errs(); 

Now we check to see if the error handler is enabled. If it is enabled, we turn of displaying all the errors to the user.

if (ERR_HANDLER_ENABLED)  // Switch off display errors @ini_set('display_errors', 0); // Set error reporting level.. error_reporting(E_ALL); > 

On the Error reporting levels, we’re going to be using E_ALL. PHP provides lots of them which you can look at here PHP Error Levels.
Here’s just a few that I think are useful together with their error codes.

Error Error Code Description
E_ERROR 1 Fatal runtime error that can be recovered, The execution of the script is stopped immediately
E_WARNING 2 A runtime warning, not fatal and most errors fall here, execution is not stopped
E_NOTICE 8 Runtime notice indicating something that could possibly be an error was encountered when running a script normally
E_COMPILE_ERROR 64 Fatal error that occurs while the script was being compiled generated by the Zend Scripting engine
E_USER_ERROR 256 A fatal user-generated error, generated by the PHP code using the function trigger_error() rather than the PHP engine
E_USER_WARNING 512 NON FATAL USER GENERATED warning message, generated by the PHP code using the function trigger_error() rather than the PHP engine
E_STRICT 2048 Not strictly an error but it’s triggered whenever PHP encounters code that could lead to problems or forward incompatibilities
E_ALL 32767 All errors and warnings except from level E_STRICT

TIP: Passing a value of (-1) to the error_reporting() function will show every possible error when new levels and constants are added in future PHP versions.

Now, we create a function that inserts a newline depending on the OS architecture.

function linending()  $newline = "\r\n"; if (isset($_SERVER["HTTP_USER_AGENT"]) && strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'win'))  $newline = "\r\n"; > else if (isset($_SERVER["HTTP_USER_AGENT"]) && strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'mac'))  $newline = "\r"; > else  $newline = "\n"; > return (defined('PHP_EOL') ? PHP_EOL : $newline); > 

This function will be called whenever a fatal error occurs.

function sysFatalErr()  global $DDEH; $error = error_get_last(); if (isset($error['type']))  if ((defined('E_ERROR') && $error['type'] == E_ERROR) || $error['type'] == 4)  $string = '[Error Code: ' . $error['type'] . '] ' . $error['message'] . linending(); $string .= '[Date/Time: ' . date('j F Y @ H:iA') . ']' . linending(); $string .= '[Fatal error on line ' . $error['line'] . ' in file ' . $error['file'] . ']'; if (ERR_HANDLER_DISPLAY)  echo '
A fatal error has occurred. For more details please view "' . ERR_HANDLER_LOG_FOLDER . '/' . FILE_FATAL_ERR_LOG_FILE . '".
'
; > $DDEH->fatalErr($string); > > >

This other function is called when general errors occur, and can further classify them accordingly. You can add more in the switch block.

function sysErrorhandler($errno, $errstr, $errfile, $errline)  global $DDEH; if (!(error_reporting() & $errno))  return; > if (!method_exists($DDEH,'generalErr') || !method_exists($DDEH,'fatalErr'))  return; > switch ($errno)  case E_USER_ERROR: $string = '[Error Code: ' . $errno . '] ' . $errstr . linending(); $string .= '[Date/Time: ' . date('j F Y @ H:iA') . ']' . linending(); $string .= '[Error on line ' . $errline . ' in file ' . $errfile . ']'; if (ERR_HANDLER_DISPLAY)  echo '
A fatal error has occurred. For more details please view "' . ERR_HANDLER_LOG_FOLDER . '/' . FILE_FATAL_ERR_LOG_FILE . '".
'
; > $DDEH->fatalErr($string); exit; break; case E_USER_WARNING: $string = '[Error Code: ' . $errno . '] ' . $errstr; $string .= '[Date/Time: ' . date('j F Y @ H:iA') . ']' . linending(); $string .= '[Error on line ' . $errline . ' in file ' . $errfile . ']'; if (ERR_HANDLER_DISPLAY) echo '
An error has occurred. For more details please view "' . ERR_HANDLER_LOG_FOLDER . '/' . FILE_ERR_LOG_FILE . '".
'
; > $DDEH->generalErr($string); break; case E_USER_NOTICE: $string = '[Error Code: ' . $errno . '] ' . $errstr . linending(); $string .= '[Date/Time: ' . date('j F Y @ H:iA') . ']' . linending(); $string .= '[Error on line ' . $errline . ' in file ' . $errfile . ']'; if (ERR_HANDLER_DISPLAY) echo '
An error has occurred. For more details please view "' . ERR_HANDLER_LOG_FOLDER . '/' . FILE_ERR_LOG_FILE . '".
'
; > $DDEH->generalErr($string); break; default: $string = '[Error Code: ' . $errno . '] ' . $errstr . linending(); $string .= '[Date/Time: ' . date('j F Y @ H:iA') . ']' . linending(); $string .= '[Error on line ' . $errline . ' in file ' . $errfile . ']'; if (ERR_HANDLER_DISPLAY) echo '
An error has occurred. For more details please view "' . ERR_HANDLER_LOG_FOLDER . '/' . FILE_ERR_LOG_FILE . '".
'
; > $DDEH->generalErr($string); break; > return true; >

Finally, we write out our errors into a file. Remember to have the logs folder created.

function write($file, $data)  file_put_contents($file, $data, FILE_APPEND); > 

You can get the whole code on the GitHub repo Here

In need of a developer for a project? Hit me Up DentriceDev Solutions

Источник

Оцените статью