PHP多种方式发送POST请求


PHP #post2014-02-17 21:12

下面列出3种发送POST请求的方法。

001function post($url, $post_data = '', $timeout = 5){//curl
002 
003    $ch = curl_init();
004 
005    curl_setopt ($ch, CURLOPT_URL, $url);
006 
007    curl_setopt ($ch, CURLOPT_POST, 1);
008 
009    if($post_data != ''){
010 
011        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
012 
013    }
014 
015    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
016 
017    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
018 
019    curl_setopt($ch, CURLOPT_HEADER, false);
020 
021    $file_contents = curl_exec($ch);
022 
023    curl_close($ch);
024 
025    return $file_contents;
026 
027}
028 
029 
030function post2($url, $data){//file_get_content
031 
032     
033 
034    $postdata = http_build_query(
035 
036        $data
037 
038    );
039 
040     
041 
042    $opts = array('http' =>
043 
044                  array(
045 
046                      'method'  => 'POST',
047 
048                      'header'  => 'Content-type: application/x-www-form-urlencoded',
049 
050                      'content' => $postdata
051 
052                  )
053 
054    );
055 
056     
057 
058    $context = stream_context_create($opts);
059 
060 
061    $result = file_get_contents($url, false, $context);
062 
063    return $result;
064 
065 
066}
067 
068 
069function post3($host,$path,$query,$others=''){//fsocket
070 
071 
072    $post="POST $path HTTP/1.1\r\nHost: $host\r\n";
073 
074    $post.="Content-type: application/x-www-form-";
075 
076    $post.="urlencoded\r\n${others}";
077 
078    $post.="User-Agent: Mozilla 4.0 yige.org\r\nContent-length: ";
079 
080    $post.=strlen($query)."\r\nConnection: close\r\n\r\n$query";
081 
082    $h=fsockopen($host,80);
083 
084    fwrite($h,$post);
085 
086    for($a=0,$r='';!$a;){
087 
088            $b=fread($h,8192);
089 
090            $r.=$b;
091 
092            $a=(($b=='')?1:0);
093 
094        }
095 
096    fclose($h);
097 
098    return $r;
099 
100}


相关文章

粤ICP备11097351号-1