Php перенаправление ошибок в файл

here’s my log function:

You can edit the log rows by editing $maxLogs=5,
also the order to write your logs $logOrder='top'

<?php
lg('script start','start');

#Code......
lg('script end','End of code');

function lg($str,$mod='Your Log Category'){
    $ts = microtime(true);
    if(!defined('logTimer')){
        define('logTimer',microtime(true));
    }
    $diff=abs(round(($ts-logTimer)*1000,2));
    $maxLogs=5;
    $logOrder='top';#new Logs at top
    
    
    $filename = './log.txt';
    $log=[];
    if(!file_exists($filename)){
        if(!file_put_contents($filename,json_encode($log,128))){
            echo "Can’t open to write '$filename' Check Permissions";
            return;
        }
    }else{
        $c=file_get_contents($filename);
        if(trim($c)==''){$c='[]';}
        
        $log =@json_decode($c,true);
        if(!is_Array($log)){$log=[];}
    }
    $new=['mod'=>$mod,'date'=> date('Y-m-d H:i:s')." Scripttime: ".$diff."ms",'log'=>$str];
    if($logOrder=='top'){
        array_unshift($log , $new);
        $log=array_slice($log,0,$maxLogs);
        }else{
        $log[]=$new;
        $log=array_slice($log,0-$maxLogs,$maxLogs);
    }
    
    
    $logs=json_encode($log,128);
    if(!file_put_contents($filename,$logs) ){echo ("Can’t open to write '$filename' Check Permissions") ;return;}
    return $str;
}
?>

The Output looks like:

[
    {
        "mod": "delete",
        "date": "2022-08-04 13:48:02 0.33ms",
        "log": "test 2"
    },
    {
        "mod": "start",
        "date": "2022-08-04 13:48:29 0ms",
        "log": "test"
    },
    {
        "mod": "delete",
        "date": "2022-08-04 13:48:29 0.27ms",
        "log": "test 2"
    },
    {
        "mod": "start",
        "date": "2022-08-04 13:48:34 0ms",
        "log": "test"
    },
    {
        "mod": "delete",
        "date": "2022-08-04 13:48:34 0.92ms",
        "log": "test 2"
    }
]

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Like Article

    In PHP, errors and warnings can be logged into a file by using a php script and changing configuration of php.ini file. Two such approaches are mentioned below:

    Approach 1: The error_log() function can be used to send error messages to a given file. First argument to the function is the error message to be sent. Second argument tells where to send/log the error message. In this case, second argument is set to 3, used to redirect error message to a file. Third argument is used to specify the file path of the error logging file.

    Below is the implementation of the above approach:

    <?php

    $error_message = "This is an error message!";

    $log_file = "./my-errors.log";

    error_log($error_message, 3, $log_file);

    ?>

    Output:

    [20-Dec-2018 17:32:00 UTC] This is an error message!

    Approach 2:

    • The init_set() function allows a user to programmatically update configuration of the php.ini file.
    • The ini_set(“log_errors”, TRUE) command can be added to the php script to enable error logging in php.
    • The ini_set(‘error_log’, $log_file) command can be added to the php script to set the error logging file.
    • Further error_log($error_message) function call can be used to log error message to the given file.

    Below is the implementation of the above approach:

    <?php

    $error_message = "This is an error message!";

    $log_file = "./my-errors.log";

    ini_set("log_errors", TRUE); 

    ini_set('error_log', $log_file);

    error_log($error_message);

    ?>

    Output:

    [20-Dec-2018 17:30:35 UTC] This is an error message!

    Similar Approach: Following lines can also be added directly to php.ini to make the configuration changes permanent for every php script that logs errors and warnings.

    log_errors = on
    error_log = ./errors.log
    

    Note:: This approach is not highly reliable as compared to other approaches. Its better to use approach 1 as it gives flexibility of choosing different files for logging at same time without changing configuration of php.ini file.

    Last Updated :
    02 Jan, 2019

    Like Article

    Save Article

    (PHP 4, PHP 5, PHP 7, PHP 8)

    error_logОтправляет сообщение об ошибке заданному обработчику ошибок

    Описание

    error_log(
        string $message,
        int $message_type = 0,
        ?string $destination = null,
        ?string $additional_headers = null
    ): bool

    Список параметров

    message

    Сообщение об ошибке, которое должно быть логировано.

    message_type

    Определяет куда отправлять ошибку.
    Возможны следующие значения:

    Типы журналов error_log()

    0 Сообщение message отправляется в системный регистратор PHP, используя
    механизм логирования операционной системы, или файл, в зависимости от значения директивы
    error_log
    в конфигурационном файле. Это значение по умолчанию.
    1 Сообщение message отправляется электронной почтой на адрес, установленный в параметре
    destination. Это единственный тип сообщения, где используется четвёртый параметр
    additional_headers.
    2 Больше не используется.
    3 message применяется к указанному в
    destination файлу. Перенос строки автоматически не добавляется в конец
    message.
    4 Сообщение message отправляется напрямую в обработчик
    логера SAPI.
    destination

    Назначение. Устанавливается в зависимости от параметра
    message_type.

    additional_headers

    Дополнительные заголовки. Используется, когда значение параметра message_type
    1.
    Данный тип сообщения использует ту же внутреннюю функцию, что и
    mail().

    Возвращаемые значения

    Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.
    Если message_type равен нулю, функция всегда возвращает true,
    независимо от того, может ли ошибка логироваться или нет.

    Список изменений

    Версия Описание
    8.0.0 Параметр destination и
    additional_headers теперь допускают значение null.

    Примеры

    Пример #1 Примеры использования error_log()


    <?php
    // Отправляет уведомление посредством серверного лога, если мы не можем
    // подключиться к базе данных.
    if (!Ora_Logon($username, $password)) {
    error_log("База данных Oracle недоступна!", 0);
    }
    // Уведомить администратора по электронной почте, если невозможно выделить ресурсы для FOO
    if (!($foo = allocate_new_foo())) {
    error_log("Большая проблема, мы выпали из FOO!", 1,
    "operator@example.com");
    }
    // другой способ вызвать error_log():
    error_log("Вы ошиблись!", 3, "/var/tmp/my-errors.log");
    ?>

    Примечания

    Внимание

    error_log() не является бинарно-безопасной функцией. message обрезается по null-символу.

    Подсказка

    message не должен содержать null-символ. Учтите, что message может передаваться в файл, по почте, в syslog и т.д. Используйте подходящую преобразующую или экранирующую функцию, base64_encode(), rawurlencode() или addslashes() перед вызовом error_log().

    kevindougans at gmail dot com

    13 years ago


    Advice to novices: This function works great along with "tail" which is a unix command to watch a log file live. There are versions of Tail for Windows too, like Tail for Win32 or Kiwi Log Viewer.

    Using both error_log() and tail to view the php_error.log you can debug code without having to worry so much about printing debug messages to the screen and who they might be seen by.

    Further Note: This works even better when you have two monitors setup. One for your browser and IDE and the other for viewing the log files update live as you go.


    Sion

    4 years ago


    DO NOT try to output TOO LARGE texts in the error_log();

    if you try to output massive amounts of texts it will either cut of the text at about 8ooo characters (for reasonable massive strings, < 32 K characters) or (for insanely massive strings, about 1.6 million characters) totally crash without even throwing an error or anything (I even put it in a try/catch without getting any result from the catch).

    I had this problem when I tried to debug a response from a wp_remote_get(); all of my error_log() worked as they should, except for ONE of them... (-_-)
    After about a day of debugging I finally found out why & that's why I type this.

    Apparently the response contained a body with over 1.6 million chars (or bytes? (whatever strlen() returns)).

    If you have a string of unknown length, use this:
    $start_index = 0;
    $end_index = 8000;
    error_log( substr( $output_text , $start_index , $end_index ) );


    frank at booksku dot com

    16 years ago


    Beware!  If multiple scripts share the same log file, but run as different users, whichever script logs an error first owns the file, and calls to error_log() run as a different user will fail *silently*!

    Nothing more frustrating than trying to figure out why all your error_log calls aren't actually writing, than to find it was due to a *silent* permission denied error!


    i dot buttinoni at intandtel dot com

    15 years ago


    Be carefull. Unexpected PHP dies when 2GByte of file log reached (on systems having upper file size limit).
    A work aorund is rotate logs :)

    php at kennel17 dot NOSPAM dot co dot uk

    17 years ago


    It appears that the system log = stderr if you are running PHP from the command line, and that often stderr = stdout.  This means that if you are using a custom error to both display the error and log it to syslog, then a command-line user will see the same error reported twice.

    Anonymous

    20 years ago


    when using error_log to send email, not all elements of an extra_headers string are handled the same way.  "From: " and "Reply-To: " header values will replace the default header values. "Subject: " header values won't: they are *added* to the mail header but don't replace the default, leading to mail messages with two Subject fields.

    <?php

    error_log

    ("sometext", 1, "zigzag@my.domain",
     
    "Subject: FoonFrom: Rizzlas@my.domainn");?>

    ---------------%<-----------------------
    To: zigzag@my.domain
    Envelope-to: zigzag@my.domain
    Date: Fri, 28 Mar 2003 13:29:02 -0500
    From: Rizzlas@my.domain
    Subject: PHP error_log message
    Subject: Foo
    Delivery-date: Fri, 28 Mar 2003 13:29:03 -0500

    sometext
    ---------------%<---------------------

    quoth the docs: "This message type uses the same internal function as mail() does." 

    mail() will also fail to set a Subject field based on extra_header data - instead it takes a seperate argument to specify a "Subject: " string.

    php v.4.2.3, SunOS 5.8


    russ at russtanner dot com

    3 years ago


    You can easily filter messages sent to error_log() using "tail" and "grep" on *nix systems. This makes monitoring debug messages easy to see during development.

    Be sure to "tag" your error message with a unique string so you can filter it using "grep":

    In your code:

    error_log("DevSys1 - FirstName: $FirstName - LastName: $Lastname");

    On your command line:

    tail -f /var/log/httpd/error_log | grep DevSys1

    In this example, we pipe apache log output to grep (STDIN) which filters it for you only showing messages that contain "DevSys1".

    The "-f" option means "follow" which streams all new log entries to your terminal or to any piped command that follows, in this case "grep".


    Matthew Swift

    3 years ago


    Relative paths are accepted as the destination of message_type 3, but beware that the root directory is determined by the context of the call to error_log(), which can change, so that one instance of error_log () in your code can lead to the creation of multiple log files in different locations.

    In a WordPress context, the root directory will be the site's root in many cases, but it will be /wp-admin/ for AJAX calls, and a plugin's directory in other cases. If you want all your output to go to one file, use an absolute path.


    paul dot chubb at abs dot gov dot au

    14 years ago


    When logging to apache on windows, both error_log and also trigger_error result in an apache status of error on the front of the message. This is bad if all you want to do is log information. However you can simply log to stderr however you will have to do all message assembly:

    LogToApache($Message) {
            $stderr = fopen('php://stderr', 'w');
            fwrite($stderr,$Message);
            fclose($stderr);
    }


    SJL

    15 years ago


    "It appears that the system log = stderr if you are running PHP from the command line"

    Actually, it seems that PHP logs to stderr if it can't write to the log file. Command line PHP falls back to stderr because the log file is (usually) only writable by the webserver.


    stepheneliotdewey at GmailDotCom

    15 years ago


    Note that since typical email is unencrypted, sending data about your errors over email using this function could be considered a security risk. How much of a risk it is depends on how much and what type of information you are sending, but the mere act of sending an email when something happens (even if it cannot be read) could itself imply to a sophisticated hacker observing your site over time that they have managed to cause an error.

    Of course, security through obscurity is the weakest kind of security, as most open source supporters will agree. This is just something that you should keep in mind.

    And of course, whatever you do, make sure that such emails don't contain sensitive user data.


    p dot lhonorey at nospam-laposte dot net

    16 years ago


    Hi !

    Another trick to post "HTML" mail body. Just add "Content-Type: text/html; charset=ISO-8859-1" into extra_header string. Of course you can set charset according to your country or Env or content.

    EG: Error_log("<html><h2>stuff</h2></html>",1,"eat@joe.com","subject  :lunchnContent-Type: text/html; charset=ISO-8859-1");

    Enjoy !


    eguvenc at gmail dot com

    14 years ago


    <?php

    //Multiline error log class

    // ersin güvenç 2008 eguvenc@gmail.com

    //For break use "n" instead 'n'
    Class log {

     
    //

     
    const USER_ERROR_DIR = '/home/site/error_log/Site_User_errors.log';

      const
    GENERAL_ERROR_DIR = '/home/site/error_log/Site_General_errors.log';
    /*

       User Errors...

      */

       
    public function user($msg,$username)

        {

       
    $date = date('d.m.Y h:i:s');

       
    $log = $msg."   |  Date:  ".$date."  |  User:  ".$username."n";

       
    error_log($log, 3, self::USER_ERROR_DIR);

        }

       
    /*

       General Errors...

      */

       
    public function general($msg)

        {

       
    $date = date('d.m.Y h:i:s');

       
    $log = $msg."   |  Date:  ".$date."n";

       
    error_log($msg."   |  Tarih:  ".$date, 3, self::GENERAL_ERROR_DIR);

        }

    }

    $log = new log();

    $log->user($msg,$username); //use for user errors

    //$log->general($msg); //use for general errors

    ?>

    franz at fholzinger dot com

    18 years ago


    In the case of missing your entries in the error_log file:
    When you use error_log in a script that does not produce any output, which means that you cannot see anything during the execution of the script, and when you wonder why there are no error_log entries produced in your error_log file, the reasons can be:
    - you did not configure error_log output in php.ini
    - the script has a syntax error and did therefore not execute

    daniel dot fukuda at gmail dot com

    13 years ago


    If you have a problem with log file permission *silently*
    it's best to leave error_log directive unset so errors will be written in your Apache log file for current VirtualHost.

    Anonymous

    2 years ago


    Depending on the error, you may also want to add an error 500 header, and a message for the user:

    $message =  'Description of the error.';
    error_log($message);
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    exit($message);


    Robert Chapin

    4 years ago


    When error_log() unexpectedly uses stdout, you should check if the php.ini value for error_log is empty in your CLI environment.  Something as simple as this might restore expected behavior:

    <?php ini_set('error_log', 'error_log'); ?>


    kazezb at nospam dot carleton dot edu

    17 years ago


    It appears that error_log() only logs the first line of multi-line log messages. To log a multi-line message, either log each line individually or write the message to another file.

    Anonymous

    13 years ago


    After scouring the internet for getting event logging to
    work in syslog on Windows 2003, I found the following
    from this post and was able to successfully get Windows
    Event Viewer to log PHP errors/notices:

    http://forums.iis.net/p/1159662/1912015.aspx#1913338

       1. Copy the PHP 5 binaries to "C:php".
       2. Right-click My Computer and select Properties to bring
    up the Computer Properties dialog. Switch to the Advanced
    tab and click Environment Variables. Find the system
    environment variable PATH, edit it and add ";C:php"
    (without the quotes) to the end.
       3. Make sure that the configuration file "php.ini" resides
    in the directory "C:php" and contains the correct path
    settings.
       4. DELETE any old "php.ini" files from "C:WINDOWS"
    and other directories.
       5. Open REGEDIT, navigate to the key
    "HKLMSOFTWAREPHP" and DELETE the string value
    "IniFilePath" from there. It is outdated and no longer
    necessary!
       6. Modify NTFS security permissions of the directory
    "C:php" to give Read and Execute permissions to (1) the
    IIS Guest Account and (2) the group IIS_WPG.
       7. Modify NTFS security permissions of the directories
    "C:phpsession" and "C:phpupload" to give additional
    Modify permissions to (1) the IIS Guest Account and (2)
    the group IIS_WPG.
       8. Navigate to the registry key
    "HKLMSYSTEMCurrentControlSetServicesEventlog
    Application" and edit the value "CustomSD" there. Find
    the substring "(D;;0xf0007;;;BG)" which Denies access to
    the application event log for Builtin Guest accounts (like
    the IIS Web User account) and replace this substring with
    "(A;;0x3;;;BG)" which allows read and write access. Please
    pay attention to leave the rest of the security string intact.
    Damaging this value can have dangerous effects!
       9. Create or update the registry key
    "HKLMSYSTEMCurrentControlSetServicesEventlogApplication
    PHP-5.2.0" (adapt the last to your version part
    if necessary) with the following values:

              * "EventMessageFile" (REG_EXPAND_SZ) = "C:phpphp5ts.dll"

              * "TypesSupported" (REG_DWORD) = 7


    PHP предлагает гибкие настройки вывода ошибок, среди которых функия error_reporting($level) – задает, какие ошибки PHP попадут в отчет, могут быть значения:

    • E_ALL – все ошибки,
    • E_ERROR – критические ошибки,
    • E_WARNING – предупреждения,
    • E_PARSE – ошибки синтаксиса,
    • E_NOTICE – замечания,
    • E_CORE_ERROR – ошибки обработчика,
    • E_CORE_WARNING – предупреждения обработчика,
    • E_COMPILE_ERROR – ошибки компилятора,
    • E_COMPILE_WARNING – предупреждения компилятора,
    • E_USER_ERROR – ошибки пользователей,
    • E_USER_WARNING – предупреждения пользователей,
    • E_USER_NOTICE – уведомления пользователей.

    1

    Вывод ошибок в браузере

    error_reporting(E_ALL);
    ini_set('display_errors', 'On'); 

    PHP

    В htaccess

    php_value error_reporting "E_ALL"
    php_flag display_errors On

    htaccess

    На рабочем проекте вывод ошибок лучше сделать только у авторизированного пользователя или в крайнем случаи по IP.

    2

    Запись ошибок в лог файл

    error_reporting(E_ALL);
    ini_set('display_errors', 'Off'); 
    ini_set('log_errors', 'On');
    ini_set('error_log', $_SERVER['DOCUMENT_ROOT'] . '/logs/php-errors.log');

    PHP

    Файлы логов также не должны быть доступны из браузера, храните их в закрытой директории с файлом .htaccess:

    Order Allow,Deny
    Deny from all

    htaccess

    Или запретить доступ к файлам по расширению .log (заодно и другие системные файлы и исходники):

    <FilesMatch ".(htaccess|htpasswd|bak|ini|log|sh|inc|config|psd|fla|ai)$">
    Order Allow,Deny
    Deny from all
    </FilesMatch>

    htaccess

    3

    Отправка ошибок на e-mail

    Ошибки можно отправлять на е-mail разработчика, но приведенные методы не работает при критических ошибках.

    Первый – register_shutdown_function() регистрирует функцию, которая выполнится при завершении работы скрипта, error_get_last() получает последнюю ошибку.

    register_shutdown_function('error_alert');
    
    function error_alert() 
    { 
    	$error = error_get_last();
    	if (!empty($error)) {
    		mail('mail@example.com', 'Ошибка на сайте example.com', print_r($error, true)); 
    	}
    }

    PHP

    Стоит учесть что оператор управления ошибками (знак @) работать в данном случаи не будет и письмо будет отправляться при каждой ошибке.

    Второй метод использует «пользовательский обработчик ошибок», поэтому в браузер ошибки выводится не будут.

    function error_alert($type, $message, $file, $line, $vars)
    {
    	$error = array(
    		'type'    => $type,
    		'message' => $message,
    		'file'    => $file,
    		'line'    => $line
    	);
    	error_log(print_r($error, true), 1, 'mail@example.com', 'From: mail@example.com');
    }
    
    set_error_handler('error_alert');

    PHP

    4

    Пользовательские ошибки

    PHP позволяет разработчику самому объявлять ошибки, которые выведутся в браузере или в логе. Для создания ошибки используется функция trigger_error():

    trigger_error('Пользовательская ошибка', E_USER_ERROR);

    PHP

    Результат:

    Fatal error: Пользовательская ошибка in /public_html/script.php on line 2
    • E_USER_ERROR – критическая ошибка,
    • E_USER_WARNING – не критическая,
    • E_USER_NOTICE – сообщения которые не являются ошибками,
    • E_USER_DEPRECATED – сообщения о устаревшем коде.

    10.10.2019, обновлено 09.10.2021

    Другие публикации

    HTTP коды

    Список основных кодов состояния HTTP, без WebDAV.

    Автоматическое сжатие и оптимизация картинок на сайте

    Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…

    Работа с JSON в PHP

    JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

    Пример парсинга html-страницы на phpQuery

    phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

    Примеры отправки AJAX JQuery

    AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

    Подключение к платежной системе Сбербанка

    После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…

    Список основных кодов состояния HTTP, без WebDAV.

    Автоматическое сжатие и оптимизация картинок на сайте

    Изображения нужно сжимать для ускорения скорости загрузки сайта, но как это сделать? На многих хостингах нет…

    Работа с JSON в PHP

    JSON (JavaScript Object Notation) – текстовый формат обмена данными, основанный на JavaScript, который представляет собой набор пар {ключ: значение}. Значение может быть массивом, числом, строкой и…

    Пример парсинга html-страницы на phpQuery

    phpQuery – это удобный HTML парсер взявший за основу селекторы, фильтры и методы jQuery, которые позволяют…

    Примеры отправки AJAX JQuery

    AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

    Подключение к платежной системе Сбербанка

    После регистрации в системе эквайринга Сбербанка и получив доступ к тестовой среде, можно приступить к интеграции с…

    Содержание:

    • Способы вывода ошибок PHP
    • Виды ошибок в файле .htaccess
    • Как включить вывод ошибок через .htaccess
    • Примеры практического применения
    • Включение журналирования ошибок PHP в .htaccess
    • Дополнительные способы вывода ошибок PHP

    Ошибки в коде — неотъемлемая часть любого процесса разработки. Чтобы понять, почему не выполняется скрипт, необходимо вывести error-логи PHP на экран.

    Следует помнить, что в публичной версии сайта вывод ошибок на экран должен быть отключён.

    • Через файл .htaccess, отвечающий за дополнительные параметры сервера Apache.
    • Непосредственно через PHP-скрипт.
    • Через файл php.ini, содержащий настройки интерпретатора PHP.

    Преимущества вывода ошибок в файле .htaccess

    1. Широкий охват. Параметры распространяются на все элементы дочерних поддиректорий.
    2. Быстрота и удобство. Обработка ошибок настраивается в несколько команд и в одном месте.

    Вывод ошибок на экран лучше делать через файл .htaccess, особенно когда PHP-файлов несколько. Поэтому далее разберём этот способ подробнее.

    Виды ошибок PHP в файле .htaccess

    • E_ALL — все виды ошибок, кроме E_STRICT до PHP 5.4.0.
    • E_ERROR — фатальные ошибки, прекращающие работу скрипта.
    • E_WARNING — ошибки-предупреждения. Не являются фатальными, поэтому не вызывают прекращение работы скрипта.
    • E_PARSE — ошибки разбора. Могут возникать только во время компиляции.
    • E_NOTICE — уведомления о нарушении времени выполнения скрипта.
    • E_CORE_ERROR — фатальная ошибка обработчика. Генерируется ядром во время запуска PHP-скрипта.
    • E_CORE_WARNING — предупреждения компиляции, возникающие при запуске PHP-скрипта.
    • E_COMPILE_ERROR — фатальные ошибки, возникающие на этапе компиляции.
    • E_COMPILE_WARNING — предупреждение компилятора PHP-скриптов.
    • E_USER_ERROR — ошибки, сгенерированные пользователями.
    • E_USER_WARNING — предупреждения, сгенерированные пользователями.
    • E_USER_NOTICE — уведомления, сгенерированные пользователями.

    Как включить вывод ошибок через .htaccess

    Файл .htaccess должен находиться в корневой директории сайта (например, «public_html»). Отредактировать его можно с помощью проводника, доступного в панели хостинга.

    Примечание. Если файла .htaccess нет, то его необходимо создать.

    Включить отображение ошибок PHP и настроить фильтрацию их вывода можно двумя директивами: «display_errors» и «error_reporting». Первая отвечает за состояние режима показа ошибок («On» или «Off»), а вторая задаёт глубину отображения.

    Показать ошибки PHP на экране можно с помощью следующего кода:

    php_flag display_errors on
    php_value error_reporting -1

    После сохранения изменённого файла, следует обновить страницу.

    Примеры практического применения

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

    Следующий код скроет ошибки PHP с экрана:

    # скрыть ошибки php
    php_flag display_startup_errors off
    php_flag display_errors off
    php_flag html_errors off
    php_value docref_root 0
    php_value docref_ext 0

    Иногда нужно фиксировать сбои, но нет возможности вывести ошибки PHP на экран  (например, сайт работает в реальном времени). Для этого можно перенаправить вывод информации в лог-файл с помощью следующего кода:

    # включить ведение журнала ошибок PHP
    php_flag  log_errors on
    # месторасположение журнала ошибок PHP
    php_value error_log /var/www/имя_пользователя/data/www/ваш_www-домен/

    Чтобы обработка ошибок в .htaccess выполнялась безопасно надо обязательно защитить папку с log-файлами от внешнего доступа при помощи следующего кода:

    # запретить доступ к журналу ошибок PHP
    <Files PHP_errors.log>
    Order allow,deny
    Deny from all
    Satisfy All
    </Files>

    Можно также настроить фильтрацию. Флаг «integer» указывает на глубину вывода данных (уровень показа). Значение «0» не выведет никаких ошибок. Комбинация «8191» запишет в log-файл сбои всех уровней.

    # общая директива для фильтрации ошибок php
    php_value error_reporting integer

    Чтобы текст ошибок не обрезался, можно установить максимальный размер на строку:

    # общая директива для установки максимального размера строки
    log_errors_max_len integer

    Выключение записи повторяющихся ошибок сократит объём поступающих данных и улучшит восприятие информации:

    # отключить запись повторяющихся ошибок
    php_flag ignore_repeated_errors on
    php_flag ignore_repeated_source on

    В результате настройки .htaccess для сайта, находящегося в публичном доступе, должны выглядеть так:

    # обработка ошибок PHP для публичного ресурса
    php_flag display_startup_errors off
    php_flag display_errors off
    php_flag html_errors off
    php_flag log_errors on
    php_flag ignore_repeated_errors off
    php_flag ignore_repeated_source off
    php_flag report_memleaks on
    php_flag track_errors on
    php_value docref_root 0
    php_value docref_ext 0
    php_value error_reporting -1
    php_value log_errors_max_len 0
    
    <Files /home/path/public_html/domain/PHP_errors.log>
    Order allow,deny
    Deny from all
    Satisfy All
    </Files>

    Во время разработки или отладки файл .htaccess должен содержать следующий код:

    # Обработка ошибок PHP во время разработки
    php_flag display_startup_errors on
    php_flag display_errors on
    php_flag html_errors on
    php_flag log_errors on
    php_flag ignore_repeated_errors off
    php_flag ignore_repeated_source off
    php_flag report_memleaks on
    php_flag track_errors on
    php_value docref_root 0
    php_value docref_ext 0
    php_value error_log /home/path/public_html/domain/PHP_errors.log
    # [see footnote 3] # php_value error_reporting 999999999
    php_value error_reporting -1
    php_value log_errors_max_len 0
    
    <Files /home/path/public_html/domain/PHP_errors.log>
    Order allow,deny
    Deny from all
    Satisfy All
    </Files>

    Включение журналирования ошибок PHP в .htaccess

    Когда отображение ошибок на странице выключено, необходимо запустить их журналирование следующим кодом:

    # включение записи PHP ошибок
    php_flag log_errors onphp_value error_log /home/path/public_html/domain/PHP_errors.log

    Примечание. Вместо «/home/path/public_html/domain/PHP_errors.log» нужно подставить собственный путь до директории, в которой будет вестись журнал ошибок.

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

    # предотвращаем доступ к логу PHP ошибок
    <Files PHP_errors.log>
    Order allow,deny
    Deny from all
    Satisfy All
    </Files>

    Дополнительные способы вывода ошибок PHP

    Можно добавить оператор «@», чтобы запретить показ ошибок в конкретной инструкции PHP:

    $value = @$var[$key];

    Вывод ошибок в PHP-скрипте

    Чтобы выводить все ошибки, нужно в начале скрипта прописать:

    error_reporting(-1);

    Если необходимо отображать ошибки PHP только из определённого места скрипта, то можно использовать следующий код:

    ini_set('display_errors', 'On'); // сообщения с ошибками будут показываться
    error_reporting(E_ALL); // E_ALL - отображаем ВСЕ ошибки
    $value = $var[$key]; // пример ошибки
    ini_set('display_errors', 'Off'); // теперь сообщений НЕ будет

    Примечание. Если заменить значения «On» и «Off» в первой и последней строках на противоположные, то на конкретном участке кода ошибки выводиться не будут.

    Через файл php.ini

    Включить или выключить показ ошибок на всём сайте/хостинге также можно с помощью файла «php.ini», в котором нужно изменить два следующих параметра:

    error_reporting = E_ALL
    display_errors On

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

    Понравилась статья? Поделить с друзьями:
  • Php ошибки в sql запросе
  • Php ошибка файл не найден
  • Php ошибка соединения с localhost
  • Php ошибка синтаксического анализа xml некорректно
  • Php ошибка при запуске приложения