php利用curl封装一个可以发送http请求的函数

curl相关参数说明如下
官网
菜鸟教程

注释都在代码里面,以便日后重复利用

/**
 * 发起http请求
 * @param string $url 目标url
 * @param string $body 需要发送的数据,json字符串之类的
 * @param string $method 请求方法,get put post delete
 * @param array $headers 请求头
 * @param bool $certPath 证书路径
 * @return void
 */
function http_request($url,$body='',$method='GET', $headers=[],$certPath=false){
    $options = [
        CURLOPT_URL => $url,
        // 将curl_exec()获取的信息以文件流的形式返回,而不是直接输出
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_INFILESIZE => -1,
        // 请求时间
        CURLOPT_TIMEOUT => 60,
        // 请求方法
        CURLOPT_CUSTOMREQUEST => $method,
        // 是否启用证书验证
        CURLOPT_SSL_VERIFYHOST => false,
        // 检查公用名是否存在,并且是否与提供的主机名匹配。 和证书验证一起使用
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_HEADER => true,
    ];
 
    if( $body != "" ) {
        $options[CURLOPT_POSTFIELDS] = $body;
    }
    // 设置method
    if( $method === "POST" ) {
        $options[CURLOPT_POST] = true;
    } else if(  $method !== "GET" ) {
        $options[ CURLOPT_CUSTOMREQUEST ] = $method;
    }
 
    if ( count($headers) )
    {
        $dataHeaders = [];
        foreach ($headers as $key => $value)
            $dataHeaders[] = $key . ': ' . $value;
 
        $options[ CURLOPT_HTTPHEADER ] = $dataHeaders;
    }
 
    if ( $certPath )
        $options[CURLOPT_CAINFO] = $certPath;
 
    $result = [];
    $result["error"] = false;
    $result["content"] = null;
 
    try
    {
        // 初始化一个 curl 会话
        if (!$curl = curl_init())
            throw new Exception('Unable to initialize cURL');
 
        if (!curl_setopt_array($curl, $options))
            throw new Exception(curl_error($curl));
 
        $response = curl_exec($curl);
        if(  $response === false ) {
            throw new Exception( curl_error($curl) );
        }
 
        $result["responseCode"] = curl_getinfo( $curl, CURLINFO_HTTP_CODE );
        $headerSize = curl_getinfo( $curl, CURLINFO_HEADER_SIZE );
        $result["content"] = substr( $response, $headerSize );
 
        //    prevent PHP from returning false
        if( !$result["content"] )
            $result["content"] = "";
 
        $result["header"] = substr( $response, 0, $headerSize );
 
        // 关闭 curl 会话资源
           curl_close($curl);
    }
    catch ( Exception $e )
    {
            $result["error"] = "CURL error: " . $e->getMessage();
    }
 
    return $result;
   }

更多的 php 怀旧小知识,可关注【php开发者社区】

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Python小叮当

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值