在标题中发送关注位置

时间:2013-06-10 11:48:26

标签: php header httpresponse

我正在尝试使用以下代码获取标头响应,以获取需要授权的链接。但响应标头为302 moved temporarily,我尝试使用CURLOPT_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;
    }
}

1 个答案:

答案 0 :(得分:0)

您必须解析$headers,如果出现Location:,则必须提出新请求。