php实现文本和图片代理,支持post,cookie

function socketopen($host, $query){
    
    $fp = fsockopen( $host, 80);
    
    if(!$fp)
        return false;
    
    $d = $c = '';
    if(!empty($_POST)){
        $way='POST';
        $c = http_build_query($_POST);
        $l = strlen($c) ;
        
        $d .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $d .= "Content-Length: $l\r\n";
        
    }else
        $way='GET';
    
    $q = "$way $query HTTP/1.1\r\n";
    $q .= "Host: ". $host ."\r\n";
    $q .= "User-Agent: ". $_SERVER['HTTP_USER_AGENT'] ."\r\n";
    $q .= "Accept: ". $_SERVER['HTTP_ACCEPT'] ."\r\n";
    $q .= "Accept-Language: ". $_SERVER['HTTP_ACCEPT_LANGUAGE'] ."\r\n";
    $q .= "Accept-Charset: GB2312,utf-8;q=0.7,*;q=0.7\r\n";
    $q .= "Connection: close\r\n";
    if(!empty($_SERVER['HTTP_COOKIE']))
        $q .= "Cookie: ". $_SERVER['HTTP_COOKIE'] ."\r\n";
    $q .= $d;
    $q .= "\r\n";
    $q .= $c;

    fputs($fp, $q);
    $results = '';
    while(!feof($fp)){
        $line = fread($fp,1024);
        $results .= $line;
    }
    fclose($fp);

    preg_match('/^HTTP(.*?)\r\n\r\n/s',$results,$ck);
    $header = $ck[0];
    checkcookie($header);
    $results = str_replace($header,'', $results);
    
    if(strstr($header,'Content-Type: image/')){
        preg_match('/Content-Type: (.*?)\r\n/',$header,$type);
        header($type[0]);
        echo $results;
        exit;
    }
    return $results;
}

function checkcookie($str){
    preg_match_all('/Set-Cookie: (.*?); /',$str,$c);
    if(!empty($c[1])){
        foreach($c[1] as $cc){
            $v = explode('=',$cc);
            $name = $v[0];
            unset($v[0]);
            setcookie($name,implode('=',$v));
        }
    }
    return true;
}

posted @ 2013-08-22 20:21  chenshuanj  阅读(468)  评论(0编辑  收藏  举报