【问题标题】:Write PHP script output in a txt file [duplicate]在txt文件中写入PHP脚本输出[重复]
【发布时间】:2020-12-21 23:10:57
【问题描述】:

我想要一种在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,但我想把这个错误写在单独的文本文件中。

【问题讨论】:

  • Monolog
  • 您可以在error_log()中设置目标文件。您也可以在 php.ini 中设置不同的文件。
  • 检查this.question的答案。 stackoverflow.com/questions/3531703/…
  • @Talk2Nit 这个问题没有回答我的问题。检查我在问题中给出的示例并了解我要登录到 txt 文件的内容。

标签: php error-handling


【解决方案1】:

您可以使用使用 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

【讨论】:

    猜你喜欢
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-24
    • 1970-01-01
    • 2016-08-17
    • 2018-08-13
    • 2019-04-21
    • 2012-12-05
    相关资源
    最近更新 更多