使用PHP,如何读取服务器的错误页面?


Using PHP, how can I read a server's error page?

我想读取服务器对某个请求的回复,根据我的需要进行修改,并将其发送给站点访问者。get_headers()工作完美的头,但如果所请求的文件丢失(404),这正是我想要使用的,get_file_contents(), readfile()和其他函数,我已经尝试了所有的警告/错误,文件丢失,而不是读取应答流到一个变量。

所以我想要的是一个类似于get_headers()的函数,只用于其余的数据,比如不取消的get_data()。有这样的事吗?

使用curl_exec。除非将CURLOPT_FAILONERROR选项设置为TRUE,否则它将始终返回正文。

下面是一个例子:

$url = 'http://www.example.com/thisrequestwillerror';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
// This is the default, but just making sure...
curl_setopt($curl, CURLOPT_FAILONERROR, false);
// Execute and return as a string
$str = curl_exec($curl);
curl_close($curl);
// Dump the response body
var_dump($str);

将其封装在一个函数中,并在应用程序中需要获取HTTP响应体的任何地方使用它。