php - 如果发生特定错误,如何在 php 中创建一个错误处理程序来重定向用户?

标签 php error-handling domparser

我正在运行一些始终运行良好的通用 php/mysql 代码,然后我运行 html dom 解析器(http://simplehtmldom.sourceforge.net/),然后我想重定向到错误页面,如果且仅当 dom 解析器发生特定错误时,但如果没有,请继续使用一些当前也可以正常工作的附加 php/mysql 脚本。这是我的代码的样子:

//First do some php/mysql operations here - these are all working fine

$html = file_get_html($website);

foreach($html->find('a[href!=#]') as $element) {
    Do several things here
}

//Then finish up with some additional php/mysql operations here - these are all working fine

大多数情况下它工作得很好,但大约 10% 的时间,取决于分配给 $website 变量的网站,我收到一个警告,然后是一个 fatal error 。例如,当我输入“https://www.liftedlandscape.com/ ” 到 $website 变量中:

Warning: file_get_contents(https://www.liftedlandscape.com/): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request in /home/test/test.test.com/simple_html_dom.php on line 75

Fatal error: Call to a member function find() on boolean in /home/test/test.com/login/create_application.php on line 148



我可以接受每隔一段时间发生的错误;我只想创建一个适本地响应错误情况的错误处理程序。我想确保 dom 解析器之前的 php/mysql 代码始终运行。然后运行 ​​dom 解析器,如果 dom 解析器功能正常,则运行脚本的其余部分,但如果 dom 解析器出现上述错误,则将用户重定向到错误页面。

我尝试了无数次迭代,但都没有成功。这是我最近的尝试:
function errorHandler($errno, $errstr) {
  echo "Error: [$errno] $errstr";
  header('Location: 
https://test.com/login/display/error_message.php');

}

//First do some other php/mysql operations here 

$html = file_get_html($website);

foreach($html->find('a[href!=#]') as $element) {
    Do several things here
}

//Then finish up with some additional php/mysql operations here

我发誓这实际上工作过一次,但之后就失败了。它只返回上面列出的相同错误而不重定向用户。有人可以帮忙吗?

最佳答案

不要通过“echo”或类似的方式发送任何输出,因为在您已经开始发送页面之后您无法重定向。

当 file_get_contents 无法完成请求时将返回 false,因此请确保在尝试使用返回的变量并假设您实际上有一些 html 可以使用之前检查它。

此外,您必须在重定向后退出以防止其余代码被处理。

$html = file_get_html($website);
if($html === false) {
  header('Location: https://test.com/login/display/error_message.php');
  exit;
}

// You can now work with $html string from here onwards.

关于php - 如果发生特定错误,如何在 php 中创建一个错误处理程序来重定向用户?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53713574/

相关文章:

php - Mysql PHP查询更新

php - 在 laravel 中还原 'php artisan serve' 命令

javascript - 无法获取命名空间元素

Java DocumentBuilder - XML 文件中的错误缩进

error-handling - 如何使用LPeg发出解析错误信号?

javascript - 使用 jquery 或 javascript 读取 xml

php - 如果缺少,将当前对象值添加到 ChoiceType 值

php - Mysql如何获取数据库中多列的SUM

reactjs - 为什么即使使用 ErrorBoundary 路由也会停止工作?

java - 什么是构造try catch语句以仅允许整数的正确方法?