ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2022-06-24 11:34:28  阅读:183  来源: 互联网

标签:ch http 请求 setopt curl php data CURLOPT 函数


分析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(filename,use_include_path,context,offset,length)

filename: 必须。要读取的文件名称,支持URI,相对/绝对路径等指定的唯一资源地址

use_include_path: 可选。如果想在include_path中搜寻文件的话,可以将参数设为“1”

context:可选。规定文件句柄的环境,contxt是一套可以修改流的行为的选项。若使用null,则忽略。

offset: 可选。规则在文件中开始读取的位置,该参数是PHP5.1新加的。

length: 可选。规定读取的字节数,该参数是PHP5.1新加的。

 

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

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

模拟POST请求

$url = 'http://192.168.1.1/test.php';
$data = array(
    'keyword' => 'test data',
);
$content = http_build_query($data);
$content_length = strlen($content);
$options = array(
    'http' => array(
        'method' => 'POST',
        'header' =>
        "Content-type: application/x-www-form-urlencoded\r\n" .
        "Content-length: $content_length\r\n",
        'content' => $content
    )
);
echo file_get_contents($url, false, stream_context_create($options));

curl发送网络请求

curl可以支持https认证、http post、ftp上传、代理、cookies、简单口令认证等等功能,使用前需要先在你的PHP环境中安装和启用curl模块,

这里有两种写法供大家参考:

<?php
function geturl($url){
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); 
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
}
 
 
function posturl($url,$data){
        $data  = json_encode($data);    
        $headerArray =array("Content-type:application/json;charset='utf-8'","Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST,FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output,true);
}
 
 
function puturl($url,$data){
    $data = json_encode($data);
    $ch = curl_init(); //初始化CURL句柄 
    curl_setopt($ch, CURLOPT_URL, $url); //设置请求的URL
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); //设为TRUE把curl_exec()结果转化为字串,而不是直接输出 
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST,"PUT"); //设置请求方式
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//设置提交的字符串
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output,true);
}
 
function delurl($url,$data){
    $data  = json_encode($data);
    $ch = curl_init();
    curl_setopt ($ch,CURLOPT_URL,$put_url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");   
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
    $output = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($output,true);
}
 
function patchurl($url,$data){
    $data  = json_encode($data);
    $ch = curl_init();
    curl_setopt ($ch,CURLOPT_URL,$url);
    curl_setopt ($ch, CURLOPT_HTTPHEADER, array('Content-type:application/json'));
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PATCH");  
    curl_setopt($ch, CURLOPT_POSTFIELDS,$data);     
    $output = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($output);
    return $output;
}
?>

一个函数片时各种请求:

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;
}

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扩展库,有起来也很方便。

 

 参考地址:https://blog.csdn.net/itopit/article/details/125240205

标签:ch,http,请求,setopt,curl,php,data,CURLOPT,函数
来源: https://www.cnblogs.com/wanghaokun/p/16408207.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有