PHP HTTP请求详细介绍

资料来源:http://www.phpernote.com/php-function/663.html    http://www.phpernote.com/php-function/664.html 

 

HTTP GET 请求

(1) file_get_contents 方式

<?php
$url='http://www.phpernote.com/php-function/654.html';
$re=file_get_contents($url);
print_r($re);

(2)curl 方式

<?php
$ch=curl_init('http://www.phpernote.com/php-function/651.html');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
$output=curl_exec($ch);
$fh=fopen("out.html",'w');
fwrite($fh,$output);
fclose($fh);

(3)fsocket方式

 

<?php
function sock_get($url){  
    $info=parse_url($url);
    $fp=fsockopen($info["host"],80,$errno,$errstr,3);
    $head="GET ".$info['path']."?".$info["query"]." HTTP/1.0\r\n";
    $head.="Host: ".$info['host']."\r\n";
    $head.="\r\n";
    $write=fputs($fp,$head);
    while(!feof($fp)){  
        $line=fgets($fp); 
        echo $line."<br>";
    }
}

 

HTTP POST请求

参考资料:http://blog.csdn.net/xingtian713/article/details/4533491 感谢博主分享
  function do_post_request($url, $data, $optional_headers = null)
  {
     $params = array('http' => array(
                  'method' => 'POST',
                  'content' => $data
               ));
     if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
     }
     $ctx = stream_context_create($params);
     $fp = @fopen($url, 'rb', false, $ctx);
     if (!$fp) {
        throw new Exception("Problem with $url, $php_errormsg");
     }
     $response = @stream_get_contents($fp);
     if ($response === false) {
        throw new Exception("Problem reading data from $url, $php_errormsg");
     }
     return $response;
  }

 

 

 

posted @ 2015-11-12 09:27  小十八  阅读(164)  评论(0)    收藏  举报