PHP使用curl和file_get_contents发送get、post请求

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/z772532526/article/details/81179108

一、file_get_contents

function get($url,$data = null)
{
    if ($data){
        $url .= '?'.http_build_query($data);//对参数编码a=b&c=d形式
    }
    return file_get_contents($url);
}
function post($url,$data = [],$json = false)
{
    if($json){
        $str = 'application/json';
        $data = json_encode($data);
    }else{
        $str = 'application/x-www-form-urlencoded';
        $data = http_build_query($data);
    }
    $options[ 'http' ] = array(
        'timeout' => 5,
        'method'  => 'POST',
        'header'  => "Content-Type: $str;charset=utf-8",
        'content' => $data,
    );
    $context = stream_context_create($options);
    return file_get_contents($url, false, $context);
}

   注意:当参数是json格式时,使用$_POST是接收不到的。应该...

json_decode(file_get_contents('php://input'),true)

二、curl

function get($url, $data = null)
{
    $ch = curl_init();
    //数据处理
    if ($data) {
        $url .= '?'.http_build_query($data);
    }
    //主要参数
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//使返回不直接输出
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//连接超时(秒)
    //执行
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}
function post($url, $data = [], $json = false)
{
    $ch = curl_init();
    //数据处理及POST参数
    if ($json) {
        $data = json_encode($data);//json编码
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-type: application/json']);//设置header
    }else {
        $data = http_build_query($data);//常规编码
        //不必额外设置header,默认x-www-form-urlencoded
    }
    curl_setopt($ch, CURLOPT_POST, true);//POST请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//装入数据
    //主要参数
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//使返回不直接输出
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);//连接超时(秒)
    
    $result = curl_exec($ch);//执行
    curl_close($ch);//关闭
    return $result;
}

对比:https://www.cnblogs.com/fangfeiyue/p/7453490.html

结论:curl在性能、速度、稳定性上都要优于file_get_contents。

PUT和DELETE及POST文件上传以后再说吧。。。

猜你喜欢

转载自blog.csdn.net/z772532526/article/details/81179108