PHP代理 - 出现错误时返回响应

时间:2011-05-29 14:17:59

标签: php

我使用PHP作为代理(用于JS XMLHttpRequest)。

在以下代码中:

  

handle = @fopen(...);

     

if(!$ handle)
  {

     

,,,

     

}

如果我输入IF,我想从服务器返回响应(标题+正文)。

我该怎么做?

3 个答案:

答案 0 :(得分:1)

使用cURL比fopen更好。它不仅更快,而且IIRC你可以更好地控制选项。

编辑:有人建议我举例说明如何使用它。最好的例子在PHP的文档中 - http://www.php.net/manual/en/curl.examples-basic.php这个例子非常接近我认为你想做的事情。您需要将CURLOPT_HEADER选项更改为1或TRUE。

您可以使用大量选项来自定义cURL的行为方式。此页面会告诉您所有内容:http://www.php.net/manual/en/function.curl-setopt.php

如果你有时间,我建议浏览cURL文档 - http://www.php.net/manual/en/book.curl.php这是一个强大的扩展,非常有用。

答案 1 :(得分:1)

fopen失败时,您可以返回您认为合适的HTTP状态,例如:

if (!$handle) {
    header('HTTP/1.1 500 Internal Server Error');
    // header('HTTP/1.1 404 Not Found');
    die();
}

答案 2 :(得分:0)

你的if语句是if(!$handle),意思是“如果fopen()失败”。如果fopen()失败,您将无法读取响应正文或标题。 fopen()的返回值是从服务器返回的数据的唯一句柄。


<强>更新

以下是如何使用error_get_last()代替$handle获取信息的示例:

<?php
$handle = fopen("http://www.google.com/doesntwork.html","r");
if (!$handle){
    $error = error_get_last();
    $m=array();
    $i = preg_match('/(HTTP\/1.[01]) ([0-9]+) (.*)/',$error['message'],$m);
    if($i){
        echo "HTTP version: ".$m[1]."<br>\n";
        echo "HTTP status: ".$m[2]."<br>\n";
        echo "HTTP message: ".$m[3]."<br>\n";
    }
} else {
    $output="";
    while(!feof($handle)){
        $output .= htmlspecialchars(fgets($handle, 1024));
    }
    fclose($handle);
    echo "fopen returned with result: $output<br>\n";
}
?>

正如另一位用户发布的那样,您最好使用fopen()包装器和/或cURL。此外,您不应该禁止警告/错误...删除@符号并修复出现的任何错误。