php发送post请求的4种方式

http://blog.163.com/fan_xy_qingyuan/blog/static/188987748201411943815244/

 

class Request{
public static function post($url, $post_data = '', $timeout = 5){//curl
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_POST, 1);
if($post_data != ''){
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
}
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HEADER, false);
$file_contents = curl_exec($ch);
curl_close($ch);
return $file_contents;
}

public static function post2($url, $data){//file_get_content
$postdata = http_build_query(
$data
);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => $postdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
return $result;
}

public static function post3($host,$path,$query,$others=''){//fsocket
    $post="POST $path HTTP/1.1\r\nHost: $host\r\n";
    $post.="Content-type: application/x-www-form-";
    $post.="urlencoded\r\n${others}";
    $post.="User-Agent: Mozilla 4.0\r\nContent-length: ";
    $post.=strlen($query)."\r\nConnection: close\r\n\r\n$query";
    $h=fsockopen($host,80);
    fwrite($h,$post);
    for($a=0,$r='';!$a;){
      $b=fread($h,8192);
      $r.=$b;
      $a=(($b=='')?1:0);
    }
    fclose($h);
    return $r;
  }
}

方法5:用fsockopen函数打开url,以POST方式获取完整的数据,包括header和body

    <?php  
    function HTTP_Post($URL,$data,$cookie, $referrer="")  
    {  
        // parsing the given URL  
    $URL_Info=parse_url($URL);  
        // Building referrer  
    if($referrer=="") // if not given use this script as referrer  
    $referrer="111";  
        // making string from $data  
    foreach($data as $key=>$value)  
    $values[]="$key=".urlencode($value);  
    $data_string=implode("&",$values);  
        // Find out which port is needed - if not given use standard (=80)  
    if(!isset($URL_Info["port"]))  
    $URL_Info["port"]=80;  
        // building POST-request:  
    $request.="POST ".$URL_Info["path"]." HTTP/1.1\n";  
    $request.="Host: ".$URL_Info["host"]."\n";  
    $request.="Referer: $referer\n";  
    $request.="Content-type: application/x-www-form-urlencoded\n";  
    $request.="Content-length: ".strlen($data_string)."\n";  
    $request.="Connection: close\n";  
        $request.="Cookie:   $cookie\n";  
        $request.="\n";  
    $request.=$data_string."\n";  
        $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);  
    fputs($fp, $request);  
    while(!feof($fp)) {  
    $result .= fgets($fp, 1024);  
    }  
    fclose($fp);  
        return $result;  
    }  
    ?> 
 

posted on 2015-04-09 12:14  傅里叶变身  阅读(328)  评论(0编辑  收藏  举报

导航