• php的curl请求,包含了post,get,put,delete


    php的curl请求,包含了post,get,put,delete

    这段代码是一个非常实用的HTTP通信工具,可以轻松集成到需要网络通信的PHP项目中。它提供了足够的灵活性,适合多种网络请求任务。

    if (!function_exists("http_curl")) {
        /**
         * 发送HTTP请求
         * @param string $url 请求的URL
         * @param array $param 请求参数
         * @param bool $https 是否使用HTTPS
         * @param string $method 请求方法,支持 GET, POST, PUT, DELETE
         * @param array $header 用户自定义的HTTP头部
         * @param int $timeout 请求超时时间(秒)
         * @param int $connectTimeout 连接超时时间(秒)
         * @param bool $followRedirects 是否跟随重定向
         * @return array 包含响应结果、HTTP状态码和其他信息的数组
         */
        function http_curl(
            string $url,
            array $param = [],
            bool $https = false,
            string $method = 'GET',
            array $header = [],
            int $timeout = 30,
            int $connectTimeout = 10,
            bool $followRedirects = false
        ) {
            $ch = curl_init();
            if (!$ch) {
                return ['success' => false, 'error' => '无法初始化cURL会话'];
            }
    
            // 准备URL和方法
            $url = prepareUrl($url, $param, $method);
            curl_setopt_array($ch, array(
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => $timeout,
                CURLOPT_CONNECTTIMEOUT => $connectTimeout,
                CURLOPT_FOLLOWLOCATION => $followRedirects,
                CURLOPT_SSL_VERIFYPEER => $https,
                CURLOPT_HTTPHEADER => prepareHeaders($header, $param, $method)
            ));
    
            // 设置请求特定的选项
            if (in_array(strtoupper($method), ['POST', 'PUT', 'DELETE'])) {
                $contentType = array_reduce($header, function ($carry, $item) {
                    if (strpos($item, 'Content-Type:') === 0) {
                        return trim(substr($item, strpos($item, ':') + 1));
                    }
                    return $carry;
                }, 'application/json');
    
                $payload = ($contentType == 'application/json') ? json_encode($param, JSON_UNESCAPED_UNICODE) : $param;
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
            }
    
            $result = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if ($result === false) {
                $error = curl_error($ch);
                $result = ['success' => false, 'error' => $error, 'http_code' => $httpCode];
            } else {
                $result = ['success' => true, 'data' => $result, 'http_code' => $httpCode];
            }
            curl_close($ch);
            return $result;
        }
    
        /**
         * 根据方法和参数准备URL
         * @param string $url 原始URL
         * @param array $param 参数数组
         * @param string $method HTTP方法
         * @return string 调整后的URL
         */
        function prepareUrl($url, $param, $method) {
            if ($method === 'GET' && !empty($param)) {
                $url .= (strpos($url, '?') === false ? '?' : '&') . http_build_query($param);
            }
            return $url;
        }
    
        /**
         * 准备请求头
         * @param array $headers 用户自定义的头部数组
         * @param array $param 请求的参数,用于确定内容长度
         * @param string $method HTTP方法
         * @return array 处理后的头部数组
         */
        function prepareHeaders($headers, $param, $method) {
            $contentTypeSet = false;
            foreach ($headers as $header) {
                if (strpos($header, 'Content-Type:') === 0) {
                    $contentTypeSet = true;
                    break;
                }
            }
    
            if (!$contentTypeSet && in_array(strtoupper($method), ['POST', 'PUT', 'DELETE'])) {
                $headers[] = 'Content-Type: application/json';
                $headers[] = 'Content-Length: ' . strlen(json_encode($param));
            }
    
            return $headers;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104

    调用案例

    // 示例调用
    $response = http_curl(
        "https://api.example.com/data",
        ['key' => 'value'],
        true,
        'POST',
      ['Authorization: Bearer your_access_token'],
        30,
        15,
        true
    );
    // 打印响应内容
    print_r($response);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    代码说明

    这段PHP代码定义了一个名为http_curl的函数,用于发送HTTP请求到指定的URL,并处理这些请求的响应。这个函数提供了灵活性来调整各种HTTP请求的参数,包括请求方法、超时时间、是否跟随重定向等。以下是对函数和它的各个部分的详细介绍:
    函数定义

    函数名: http_curl
    参数:
        string $url: 请求的目标URL。
        array $param = []: 发送请求时用的参数数组,缺省为一个空数组。
        bool $https = false: 指示是否使用HTTPS进行请求,默认为false。
        string $method = 'GET': HTTP请求方法,默认为GET。支持GET, POST, PUT, DELETE。
        array $header = []: 用户自定义的HTTP头部数组,默认为空数组。
        int $timeout = 30: 请求的超时时间,默认为30秒。
        int $connectTimeout = 10: 连接的超时时间,默认为10秒。
        bool $followRedirects = false: 是否自动跟随HTTP重定向,默认为false。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    函数体

    初始化: 使用curl_init初始化cURL会话。
    
    准备URL: 通过调用prepareUrl函数,根据HTTP方法和提供的参数来准备或修改URL。
    
    设置cURL选项:
        CURLOPT_URL: 设置请求的URL。
        CURLOPT_RETURNTRANSFER: 设置为true以返回请求的结果而非直接输出。
        CURLOPT_TIMEOUT 和 CURLOPT_CONNECTTIMEOUT: 分别设置请求和连接的超时时间。
        CURLOPT_FOLLOWLOCATION: 设置是否跟随重定向。
        CURLOPT_SSL_VERIFYPEER: 根据$https参数确定是否验证对等证书。
        CURLOPT_HTTPHEADER: 使用prepareHeaders函数准备HTTP头部。
    
    设置请求方法和负载:
        如果方法是POST, PUT, DELETE,则设置CURLOPT_CUSTOMREQUEST为相应的方法,并准备负载(参数),这取决于Content-Type。
    
    执行请求:
        使用curl_exec执行cURL请求。
        获取HTTP状态码。
        检查是否有错误,如果有,返回错误信息和状态码。
    
    关闭cURL会话:
        使用curl_close结束cURL会话。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    结果返回

    函数返回一个数组,包含是否成功的标志、数据(或错误信息)、HTTP状态码等。
    辅助函数

    prepareUrl: 根据方法和参数调整URL。
    prepareHeaders: 准备HTTP头部,自动添加内容类型和内容长度,如果请求方法为POST, PUT, DELETE且未设置Content-Type。
    
    • 1
    • 2
  • 相关阅读:
    【Java】数组的深浅拷贝问题(二维数组举例)(136)
    java计算机毕业设计盘山县智慧项目管理系统源码+系统+数据库+lw文档+mybatis+运行部署
    java-net-php-python-springboot区校企大型仪器智慧共享平台计算机毕业设计程序
    开源现场总线协议栈
    【数据库】数据库绪论,你都会了吗
    【逻辑与计算机设计】数码系统和数字系统 | Digital systems and number systems
    基于阶梯式Tent混沌和模拟退火的樽海鞘群算法
    【教3妹学java】Java之happens-before是什么?
    解释器-架构案例2021(三十一)
    【基于pyAudioKits的Python音频信号处理(四)】傅里叶变换:从时域到频域
  • 原文地址:https://blog.csdn.net/weixin_44213550/article/details/138204851