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

How do I create an error handler in php that redirects the user if a specific error occurs?

我正在 运行 宁一些通用的 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 变量的网站,我会收到警告,然后是致命错误。例如,当我将“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 代码总是 运行s。然后 运行 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 在无法完成请求时将 return 为假,因此请确保在尝试使用 returned 变量并假设您确实有一些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.