0

我正在尝试使用以下代码获取标头响应以获取需要授权的链接。但是响应标头是302 moved temporarily,我尝试使用 curlCURLOPT_FOLLOWLOCATION和响应标头是200 ok

那么我怎样才能让下面的代码像 curl 一样工作呢?

function get_headers_x($url,$format=0, $user='', $pass='', $referer='') {
    if (!empty($user)) {
        $authentification = base64_encode($user.':'.$pass);
        $authline = "Authorization: Basic $authentification\r\n";
    } else $authline = '';

    if (!empty($referer)) {
        $refererline = "Referer: $referer\r\n";
    } else $refererline = '';

    $url_info=parse_url($url);
    $port = isset($url_info['port']) ? $url_info['port'] : 80;
    $fp=fsockopen($url_info['host'], $port, $errno, $errstr, 30);
    if($fp) {
        $head = "GET ".@$url_info['path']."?".@$url_info['query']." HTTP/1.0\r\n";
        if (!empty($url_info['port'])) {
            $head .= "Host: ".@$url_info['host'].":".$url_info['port']."\r\n";
        } else {
            $head .= "Host: ".@$url_info['host']."\r\n";
        }
        $head .= "Connection: Close\r\n";
        $head .= "Accept: */*\r\n";
        $head .= "Location: 1 \r\n";
        $head .= $refererline;
        $head .= $authline;
        $head .= "\r\n";

        fputs($fp, $head);      
        while(!feof($fp) or ($eoheader==true)) {
            if($header=fgets($fp, 1024)) {
                if ($header == "\r\n") {
                    $eoheader = true;
                    break;
                } else {
                    $header = strtolower(trim($header));
                }

                if($format == 1) {
                    $ex = explode(':',$header);
                    $key = array_shift($ex);
                    if($key == $header) {
                        $headers[] = $header;
                    } else {
                        $headers[$key]=substr($header,strlen($key)+2);
                    }
                    unset($key);
                } else {
                    $headers[] = $header;
                }
            }
        }
        return $headers;

    } else {
        return false;
    }
}
4

1 回答 1

0

你必须解析$headers,如果Location:出现,你必须提出一个新的请求。

于 2013-06-10T12:02:03.707 回答