Catching Failed HTTP Request in PHP

点点圈 提交于 2019-12-06 06:12:14

The reason you are still getting the error is because of this line:

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

When getWordList gets a 404 from file_get_contents(), FALSE is returned and that is generating the exception about the invalid argument getting passed.

One thing you could try to do to fix it is this:

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

That should at least handle URLs it cant load.

Wrap it all in a try-catch block. PHP has a mechanism for handling those fatal errors.

Something like this should work:

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

Here's some documentation on the construct: http://php.net/manual/en/language.exceptions.php

You'll probably want to determine exactly which line of code is causing the error, and use the most specific subclass of Exception that you can. This is a best practice, since you don't want to miss exceptions that are unrelated to this issue.

The best thing you can do is switch to using cURL. While you can get the errors when using file_get_contents(), it isn't very robust.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!