php curl的get/post/delete/put请求

function curl_request($url, $data = null, $method = 'post', $header = ['Accept: text/xml,application/xml,application/xhtml+xml,'], $https = true, $timeout = 10)
{
   // 常用的header头
   //$header[] = "Accept: text/xml,application/xml,application/xhtml+xml,";
  //$header[]= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  //$header[] = "Cache-Control: max-age=0";
  //$header[] = "Connection: keep-alive";
  //$header[] = "Keep-Alive: 300";
  //$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7";
  //$header[] = "Accept-Language: en-us,en;q=0.5";
  //$header[] = "Pragma: "; // browsers keep this blank.
    $method = strtoupper($method);
    //初使化init方法
    $ch = curl_init();
    //指定URL
    curl_setopt($ch, CURLOPT_URL, $url);
    //设定请求后返回结果
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//只获取页面内容,但不输出
    if ($https) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);//https请求 不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);//https请求 不验证HOST
    }
    if ($method != "GET") {

        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);//请求方式为post请求
        }
        if ($method == 'PUT' || strtoupper($method) == 'DELETE') {
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); //设置请求方式
        }
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//请求数据
    }
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
    //curl_setopt($ch, CURLOPT_HEADER, false);//设置不需要头信息
    $result = curl_exec($ch);//执行请求
    curl_close($ch);//关闭curl,释放资源
    return $result;
}
发布了68 篇原创文章 · 获赞 10 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/dw5235/article/details/102963257