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

sinmu phper 2022-02-12 14:41:22

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;
}
...全文
175 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
creatorwpy 2024-03-13
  • 打赏
  • 举报
回复

\强

15

社区成员

发帖
与我相关
我的任务
社区描述
我可以对一件事情坚持下去吗
社区管理员
  • Python小叮当
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

佛系记录php的相关知识

试试用AI创作助手写篇文章吧