一、分析php发送网网络请求的方法

    对于php发送网络请求,我们最常用的请求就是curl,有时我们也会用到file_get_contents函数发送网络请求,但file_get_contents只能完成一些间单的网络请求,稍复杂的就无法完成,例如文件上传,cookies,验证,表单提交等,用php的curl可以使用URL的语法模拟浏览器来传输数据,因为它是模拟浏览器,因此它同样支持多种协议,FTP, FTPS, HTTP, HTTPS, GOPHER, TELNET, DICT, FILE 以及 LDAP等协议都可以很好的支持,包括一些:HTTPS认证,HTTP POST方法,HTTP PUT方法,FTP上传,keyberos认证,HTTP上传,代理服务器,cookies,用户名/密码认证,下载文件断点续传,上传文件断点续传,http代理服务器管道,甚至它还支持IPv6,scoket5代理服务器,通过http代理服务器上传文件到FTP服务器等等,所以我们在开发中尽量用curl发网络请求,无论是简单还是复杂

    二、file_get_contents发送网络请求示例

    file_get_contents(path,include_path,context,start,max_length)

    php实现网络请求的方法及函数总结 - 图1

    一般用file_get_contents或者fopen, file , readfile等函数读取url的时候 会创建一个$http_response_header变量保存HTTP响应的报头,使用fopen等函数打开的数据流信息可以用stream_get_meta_data获取

    1. $html = file_get_contents('http://www.baidu.com');
    2. print_r($http_response_header);
    3. $fp = fopen('http://www.baidu.com', 'r');
    4. print_r(stream_get_meta_data($fp));
    5. fclose($fp);

    摸拟post请求:

    1. $url = 'http://192.168.1.1/test.php';
    2. $data = array(
    3. 'keyword' => 'test data',
    4. );
    5. $content = http_build_query($data);
    6. $content_length = strlen($content);
    7. $options = array(
    8. 'http' => array(
    9. 'method' => 'POST',
    10. 'header' =>
    11. "Content-type: application/x-www-form-urlencoded\r\n" .
    12. "Content-length: $content_length\r\n",
    13. 'content' => $content
    14. )
    15. );
    16. echo file_get_contents($url, false, stream_context_create($options));

    三、php 用curl发送网络请求

    curl可以支持https认证、http post、ftp上传、代理、cookies、简单口令认证等等功能,使用前需要先在你的PHP环境中安装和启用curl模块,这里有两种写法供大家参考:

    1. <?php
    2. function geturl($url){
    3. $headerArray =array("Content-type:application/json;","Accept:application/json");
    4. $ch = curl_init();
    5. curl_setopt($ch, CURLOPT_URL, $url);
    6. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    7. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    8. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    9. curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
    10. $output = curl_exec($ch);
    11. curl_close($ch);
    12. $output = json_decode($output,true);
    13. return $output;
    14. }
    15. function posturl($url,$data){
    16. $data = json_encode($data);
    17. $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
    18. $curl = curl_init();
    19. curl_setopt($curl, CURLOPT_URL, $url);
    20. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    21. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
    22. curl_setopt($curl, CURLOPT_POST, 1);
    23. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    24. curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
    25. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    26. $output = curl_exec($curl);
    27. curl_close($curl);
    28. return json_decode($outputtrue);
    29. }
    30. function puturl($url,$data){
    31. $data = json_encode($data);
    32. $ch = curl_init(); //初始化CURL句柄
    33. curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
    34. curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    35. curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出
    36. curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
    37. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
    38. $output = curl_exec($ch);
    39. curl_close($ch);
    40. return json_decode($output,true);
    41. }
    42. function delurl($url,$data){
    43. $data = json_encode($data);
    44. $ch = curl_init();
    45. curl_setopt ($ch,CURLOPT_URL,$put_url);
    46. curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    47. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    48. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    49. curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    50. $output = curl_exec($ch);
    51. curl_close($ch);
    52. $output = json_decode($output,true);
    53. }
    54. function patchurl($url,$data){
    55. $data = json_encode($data);
    56. $ch = curl_init();
    57. curl_setopt ($ch,CURLOPT_URL,$url);
    58. curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    59. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    60. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PATCH");
    61. curl_setopt($ch, CURLOPT_POSTFIELDS,$data); //20170611修改接口,用/id的方式传递,直接写在url中了
    62. $output = curl_exec($ch);
    63. curl_close($ch);
    64. $output = json_decode($output);
    65. return $output;
    66. }
    67. ?>

    一个函数片时各种请求:

    function sendCurl($url, $data = null,$method='POST')
    {
        $method=strtoupper($method);
        $start_wdmcurl_time = microtime(true);
    
        $header = array(' application/x-www-form-urlencoded');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        // https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https")
        {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        if($method=='GET'){
            if($data && is_array($data) && count($data)>0 ){
                $url.="?".http_build_query($data);
            }
            curl_setopt($ch, CURLOPT_URL, $url);
        }elseif($method=='POST'){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            if (is_array($data) && count($data)>0)
            {
                curl_setopt($ch, CURLOPT_POST, true);
                $isPostMultipart = false;
                foreach ($data as $k => $v)
                {
                    if ('@' == substr($v, 0, 1))
                    {
                        $isPostMultipart = true;
                        break;
                    }
                }
                unset($k, $v);
                if ($isPostMultipart) {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
                } else {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
                }
            }
        }elseif(in_array($method,['PUT','DELETE','PATCH'])){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,$method);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
        $reponse = curl_exec($ch);
        curl_close($ch);
        return $reponse;
    }
    

    四、使用php composer的扩展guzzlehttp

    composer require guzzlehttp/guzzle
    
    
    $client = new \GuzzleHttp\Client();
    $response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
    
    echo $response->getStatusCode(); // 200
    echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
    echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'
    
    // Send an asynchronous request.
    $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
    $promise = $client->sendAsync($request)->then(function ($response) {
        echo 'I completed! ' . $response->getBody();
    });
    
    $promise->wait();
    

    日常开发中我们尽量用方法三,自定义用curl处理网络请求,或用composer的guzzlehttp扩展库,有起来也很方便。