【问题标题】:PHP - How to suppress individual warnings in error log file?PHP - 如何抑制错误日志文件中的个别警告?
【发布时间】:2017-06-12 20:17:56
【问题描述】:

我的脚本从网站上抓取数据。每当该网站不可用时,我的 error_log 文件中就会出现这样的错误:

[UTC 时间 2017 年 6 月 3 日 15:00:03] PHP 警告:文件(http://example.com): 无法打开流:HTTP 请求失败! HTTP/1.1 503 服务 不可用

有一个similar question here,但我只想禁止个人警告 - 因为我希望我的脚本中的任何其他警告仍然被记录。

那么是否可以禁止来自各个行的警告?

我已经尝试在 try/catch 块中包围给出警告的代码行 - 即,

try {
    $lines = file("https://example.com"); // This line results in a warning in my error_log file if the web page is currently unavailable
}
catch(Exception $e) {
}

但我仍然收到警告。有没有人有其他想法?

【问题讨论】:

  • 尝试使用这个:error_reporting(E_ERROR | E_PARSE); 这是因为警告不是例外=>你不能抓住它。我建议在生产中关闭警告....
  • 谢谢,但这不会抑制所有其他警告(我想保留)吗?
  • 是的,下一个讨厌的选项是:@file("https://example.com");php.net/manual/en/language.operators.errorcontrol.php
  • 如果我将我的 $lines = file("https://example.com"); 代码行移动到一个单独的 php 文件,然后仅在该文件中设置 error_reporting(...) 会怎样。这行得通吗?
  • 我会使用@运算符,然后检查$lines中是否有任何内容

标签: php


【解决方案1】:

抑制错误几乎在所有情况下都是无稽之谈。一个适当的解决方案是检查返回的 HTTP 状态代码,并且只有在它有效的情况下 - 使用文件。

例如(未测试,遗憾的是 3v4l 不支持 cURL):

<?php
    function checkDomain($domain) {
        $handle = curl_init($url);
        $success = true;
        curl_setopt($handle,  CURLOPT_RETURNTRANSFER, TRUE);

        /* Get the HTML or whatever is linked in $url. */
        $response = curl_exec($handle);

        /* Check for 404 (file not found). */
        $httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
        if($httpCode == 503) {
            $success = false;
        }


        curl_close($handle);
        return $success;
    }

    $domain = 'http://www.goweogweog.de';
    if(checkDomain($domain)) { // GOOD
        file($domain);
    }

    file($domain); // BAD

【讨论】:

  • 好的,谢谢。是否可以在不发出额外请求的情况下检查 HTTP 状态码?
  • @ban-geoengineering 是 - 停止使用 file() 处理 url 及其响应,并使用 curl 获取响应。
  • 谢谢,但即使我将 curl_setopt($handle, CURLOPT_NOBODY, true); 添加到您的代码中,我仍然会发出两个请求 - 一个通过 cURL 和一个通过 file($domain)。是否可以通过一次调用进行检查和(如果代码 200)检索?
  • @ban-geoengineering 是的,正如我所说 - 完全停止使用 file() - 使用 $response = curl_exec($handle) 并正确解析输出。
  • 您能否相应地更新您的代码,因为它目前似乎正在使用两者?
【解决方案2】:

看起来你可以在脚本中切换错误报告状态:

error_reporting(E_ALL); // Report all errors/warnings/notices
$lines = file("https://111111asegfiwaehflewakfhewaflk.err"); // Warning logged

error_reporting(E_ERROR | E_PARSE); // Don't report warnings
$lines = file("https://222222asegfiwaehflewakfhewaflk.err"); // Warning NOT logged

error_reporting(E_ALL); // Report all errors/warnings/notices
$lines = file("https://333333asegfiwaehflewakfhewaflk.err"); // Warning logged

Xatenev's answer 是一种更好的方法,但我发布此答案是因为它回答了原始问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 2017-12-14
    • 2017-08-12
    • 1970-01-01
    相关资源
    最近更新 更多