php - 将 PHP 脚本输出写入 txt 文件

标签 php error-handling

这个问题在这里已经有了答案:





How do I log errors and warnings into a file?

(7 个回答)



How to write to error log file in PHP [closed]

(4 个回答)


1年前关闭。




我想要一种在 PHP 中写入错误和警告的方法脚本或脚本的输出,例如 echo "Hello World";在文本文件中
我不认为error_log()函数对我来说很有用,因为这个函数记录了我之前在代码中提到的错误。
我想要的是这样的
PHP 代码

<?php

echo "Your Name is ".$name; // $name here is not defined 

?>
此脚本将给出以下错误
Notice: Undefined variable: name in C:\wamp64\www\example.php on line 3
此错误将自动写入我的服务器中的 php_error.log,但我想将此错误写入单独的文本文件中。

最佳答案

您可以使用使用 set_error_handler 设置的自定义错误处理程序来执行此操作。功能

<?php

function handleError($errorNumber, $errorString, $errorFile, $errorLine, array $errContext)
{
    // Path to log file
    $logFilePath = 'errors.log';

    // Do we want to prevent the default PHP error handler from executing?
    $allowDefaultLogging = true;

    // error was suppressed with the @-operator do not log and cancel the default error handler
    if (0 === error_reporting())
    {
        return false;
    }

    // Build log message string from error components
    $message = $errorFile . ':' . $errorLine . ' errno ' . $errorNumber . ' ' . $errorString . PHP_EOL;

    // Open the file for writing, append, create file if it does not exist
    $logHandle = fopen($logFilePath, 'a+');

    // Write the error message
    fwrite($logHandle, $message);

    // Close the file handle
    fclose($logHandle);

    // Tell PHP whether or not to handle the error with the default handler
    return $allowDefaultLogging;
}

// Tell PHP we want errors to go to our custom handler
set_error_handler('handleError');

echo "Your Name is " . $name . PHP_EOL; // $name here is not defined

关于php - 将 PHP 脚本输出写入 txt 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63711343/

相关文章:

php - 是否可以有一个具有私有(private)/ protected 方法的接口(interface)?

exception - 何时对域类中的异常使用断言

sql-server - SQL Server : conversion error when attempting to load 'smallmoney' data into table

javascript - 重定向至手机版,同时仍保留域名

php - 该数据是否被另一个组件覆盖?

php - 如何使用 avconv 连接一系列视频

php - 无法使用表单发布到数据库

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

python - 赋值之前引用的局部变量/Python

python - Flask 自定义错误页面 500 不工作