开发者

PHP proxy - return response in case of error

开发者 https://www.devze.com 2023-03-08 21:38 出处:网络
I use PHP as proxy (for JS XMLHttpRequest). In the following code: 开发者_运维问答handle = @fopen(...);

I use PHP as proxy (for JS XMLHttpRequest).

In the following code:

开发者_运维问答handle = @fopen(...);

if (!$handle)

{

,,,

}

I want to return the response (header + body) from the server in case i enter the IF.

How can i do that?


You could return the HTTP status you think is appropriate when fopen fails, e.g.:

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


You're better off using cURL than fopen. Not only is it faster, but IIRC you have finer-grained control over the options.

Edit: It's been suggested that I give an example of how to use this. The best examples are within PHP's documentation - http://www.php.net/manual/en/curl.examples-basic.php This example is pretty close to what I think you're wanting to do. You'd need to change the CURLOPT_HEADER option to 1 or TRUE.

There are a ton of options you can use to customize how cURL behaves. This page will tell you everything: http://www.php.net/manual/en/function.curl-setopt.php

If you've got the time, I'd recommend skimming through the cURL documentation - http://www.php.net/manual/en/book.curl.php It's a powerful extension and very useful.


Your if statement says if(!$handle), meaning "if fopen() fails". If fopen() fails, you're not going to be able to read a response body or header. The return value from fopen() is the only handle to the data coming back from the server.


UPDATE:

Here's an example of how to get the information using error_get_last() instead of $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";
}
?>

As another user posted, you're better off using fopen() wrappers and/or cURL. Also, you shouldn't suppress warnings/errors...remove the @ symbol and fix any errors that come up.

0

精彩评论

暂无评论...
验证码 换一张
取 消