【问题标题】:Catching Failed HTTP Request in PHP在 PHP 中捕获失败的 HTTP 请求
【发布时间】:2012-05-02 12:37:46
【问题描述】:

所以,我在使用 file_get_contents 的 PHP 中遇到了一点麻烦...

我正在使用this code

之前,如果我使用找不到的哈希 (bdfccf20b1db88d835c27685ac39f874) 运行它,它会返回:

fcf1eed8596699624167416a1e7e122e - found: octopus (Google)
bed128365216c019988915ed3add75fb - found: passw0rd (Google)
d0763edaa9d9bd2a9516280e9044d885 - found: monkey (Google)
dfd8c10c1b9b58c8bf102225ae3be9eb - found: 12081977 (Google)
ede6b50e7b5826fe48fc1f0fe772c48f - found: 1q2w3e4r5t6y (Google)
bdfccf20b1db88d835c27685ac39f874
Warning: file_get_contents(http://md5.gromweb.com/query/bdfccf20b1db88d835c27685ac39f874): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

 in /Users/mihir/MD5Decryptor.php on line 44

Catchable fatal error: Argument 2 passed to MD5Decryptor::dictionaryAttack() must be an array, boolean given, called in /Users/mihir/MD5Decryptor.php on line 56 and defined in /Users/mihir/MD5Decryptor.php on line 25

为了停止警告,我改变了

if ($response = file_get_contents($url)) {

在第 43 行到

$response = @file_get_contents($url);
if ($response) {

输出变成了

fcf1eed8596699624167416a1e7e122e - found: octopus (Google)
bed128365216c019988915ed3add75fb - found: passw0rd (Google)
d0763edaa9d9bd2a9516280e9044d885 - found: monkey (Google)
dfd8c10c1b9b58c8bf102225ae3be9eb - found: 12081977 (Google)
ede6b50e7b5826fe48fc1f0fe772c48f - found: 1q2w3e4r5t6y (Google)
bdfccf20b1db88d835c27685ac39f874
Catchable fatal error: Argument 2 passed to MD5Decryptor::dictionaryAttack() must be an array, boolean given, called in /Users/mihir/MD5Decryptor.php on line 56 and defined in /Users/mihir/MD5Decryptor.php on line 25

如何发现错误?如,如果未找到哈希,我如何修改脚本以返回“未找到哈希”而不完全崩溃?

提前谢谢...

【问题讨论】:

    标签: php file-get-contents


    【解决方案1】:

    您仍然收到错误的原因是因为这一行:

    return $this->dictionaryAttack($hash, $this->getWordlist($hash));
    

    当 getWordList 从 file_get_contents() 获得 404 时,FALSE 被返回,这将生成有关传递无效参数的异常。

    您可以尝试做的一件事是:

    $list = $this->getWordlist($hash);
    if ($list === false) {
        return 'Error fetching URL';
    } else {
        return $this->dictionaryAttack($hash, $list);
    }
    

    至少应该处理它无法加载的 URL。

    【讨论】:

    • 或者,如果我没记错的话,第 42 行的 $list = FALSE 可以替换为 $list = array()
    【解决方案2】:

    将它全部包装在一个 try-catch 块中。 PHP 有处理这些致命错误的机制。

    这样的事情应该可以工作:

    try {
        if ($response = file_get_contents($url)) {
            ...
        }
    }
    catch (Exception $e) {
        // return your "Hash Not Found" response
    }
    

    以下是有关构造的一些文档: http://php.net/manual/en/language.exceptions.php

    您可能希望准确确定导致错误的代码行,并尽可能使用最具体的 Exception 子类。这是一种最佳做法,因为您不想错过与此问题无关的异常。

    【讨论】:

      【解决方案3】:

      你能做的最好的事情是switch to using cURL。虽然你 can get the errors when using file_get_contents(),但它不是很健壮。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 2010-10-16
      • 1970-01-01
      • 2016-09-07
      • 2014-11-19
      相关资源
      最近更新 更多