在PHP中捕获失败的HTTP请求

在PHP中捕获失败的HTTP请求,php,file-get-contents,Php,File Get Contents,所以,我在PHP中遇到了一点问题,文件内容 我正在使用 之前,如果我使用无法找到的哈希(bdfccf20b1db88d835c27685ac39f874)运行它,它将返回以下内容: fcf1eed8596699624167416a1e7e122e - found: octopus (Google) bed128365216c019988915ed3add75fb - found: passw0rd (Google) d0763edaa9d9bd2a9516280e9044d885 - found

所以,我在PHP中遇到了一点问题,文件内容

我正在使用

之前,如果我使用无法找到的哈希(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
我怎样才能抓住错误?如中所示,如果没有找到散列,我如何修改脚本以返回“hash not found”而不完全崩溃


提前感谢…

你能做的最好的事情就是。但是,它不是很健壮。

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

像这样的方法应该会奏效:

try {
    if ($response = file_get_contents($url)) {
        ...
    }
}
catch (Exception $e) {
    // return your "Hash Not Found" response
}
以下是有关该构造的一些文档:


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

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

return $this->dictionaryAttack($hash, $this->getWordlist($hash));
当getWordList从
文件\u get\u contents()
获取404时,将返回
FALSE
,这将生成有关传递无效参数的异常

您可以尝试做一件事来修复它:

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

这至少可以处理它无法加载的URL。

Hmm。。。我在卷发方面没有多少经验。我将如何以及在何处实施它?@MihirSingh,我刚刚添加了一个链接来帮助您开始。另请参见:您也可以使用file_get_内容控制错误处理,只需使用HTTP上下文即可。工作非常出色,不比curl IMHO差。或者,如果我没有弄错的话,第42行的
$list=FALSE
可以替换为
$list=array()