Encapsulated PHP sends HTTP requests with curl. Get and post are very easy to use

Time:2021-11-29

It encapsulates a relatively complete curl request function,Compatible with get and post, content format compatible with JSON and x-www-form-urlencoded, HTTP and HTTPS。 And wrote very detailed comments. People in need can customize and modify the code according to the comments to achieve the desired effect. Environmental requirements php7

Direct code

if (!function_exists('curl_request')) {
    /**
     *Notes: curl send HTTP request
     *User: hear the bell in the rain at night
     *@ param string $URL URL requested URL
     * @param bool $is_ Is post a post request
     *@ param array $data request parameters
     *@ param array $header request header Description: the request header should be formatted in this way to take effect ['authorization: 0f5fc4730e21048eae936e2eb99de548 ']
     * @param bool $is_ Whether JSON is a JSON request. The default is content type: application / x-www-form-urlencoded
     * @param int $time_ Out timeout is in seconds, 0 will never timeout
     * @return mixed
     */
    function curl_request(string $url, bool $is_post = true, array $data = [], array $header = [], bool $is_json = false, int $time_out = 0)
    {
        if (empty($url)) {
            return  false;
        }

        //Initialize curl
        $curl = curl_init();

        //If the curl version is greater than 7.28.1, it must be 2. The curl version of PHP 7.0 is 7.40.1. If you use php7 or above, you can ensure that there is no problem
        $ssl = (strpos($url,'https') !== false) ? 2 : 0;
        $options = [
            //Set URL
            CURLOPT_URL => $url,

            //The information of the header file is output as a data stream
            CURLOPT_HEADER => false,

            //The request result is returned as a string and is not output directly
            CURLOPT_RETURNTRANSFER => true,

            //Disable curl validation of peer certificates
            CURLOPT_SSL_VERIFYPEER => false,

            //Identity "," deflate "," gzip ", three encoding methods. If it is set as an empty string, it means that three encoding methods are supported. When there is garbled code, this string can be set
            CURLOPT_ENCODING => '',

            //Set HTTP version. HTTP 1.1 is the mainstream HTTP version
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,

            //The maximum waiting time when connecting to the other host. When it is set to 10 seconds, if the other server does not respond within 10 seconds, it will actively disconnect the link. If 0, the server response time is not limited
            CURLOPT_CONNECTTIMEOUT => $time_out,

            //The longest waiting time of the whole curl function execution process, that is, this time includes the connection waiting time
            CURLOPT_TIMEOUT => 0,

            //Check if a common name exists in the server SSL certificate
            CURLOPT_SSL_VERIFYHOST => $ssl,

            //Set header information
            CURLOPT_HTTPHEADER => $header
        ];

        //Post and get special handling
        if ($is_post) {
            //Set post request
            $options[CURLOPT_POST] = true;

            if ($is_json && $data) {
                //JSON processing
                $data = json_encode($data);
                $header = array_merge($header, ['Content-Type: application/json']);
                //Set header information
                $options[CURLOPT_HTTPHEADER] = $header;

                //If it is a JSON string, HTTP cannot be used_ build_ Query function
                $options[CURLOPT_POSTFIELDS] = $data;
            } else {
                //X-www-form-urlencoded processing
                //If it is an array, add http_ build_ Query. If it is not added, an error will be reported when encountering a two-dimensional array.
                $options[CURLOPT_POSTFIELDS] = http_build_query($data);
            }
        } else {
            // GET
            $options[CURLOPT_CUSTOMREQUEST] = 'GET';

            //No? And the data is not empty. Splice the parameters into the URL
            if (strpos($url,'?') === false && !empty($data) && is_array($data)) {
                $params_arr = [];
                foreach ($data as $k => $v) {
                    array_push($params_arr,$k . '=' . $v);
                }
                $params_string = implode('&',$params_arr);
                $options[CURLOPT_URL] = $url . '?' . $params_string;
            }
        }

        //Setting curl in array mode is better than using curl multiple times_ Set the setopt function to be faster
        curl_setopt_array($curl,$options);

        //Execute request
        $response = curl_exec($curl);

        //Returned content_ Type type
        $content_type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);

        //Returned HTTP status code
        $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        //Curl when there are no errors_ Errno returns 0
        if (curl_errno($curl) == 0) {
            $result = [
                'HTTP_MSG' => 'SUCCESS',
                'HTTP_BODY' => json_decode($response, true),
                'HTTP_HEADER' => $content_type,
                'HTTP_CODE' => $http_code,
            ];
        } else {
            $result = [
                'HTTP_MSG' => curl_error($curl),
                'HTTP_BODY' => null,
                'HTTP_HEADER' => $content_type,
                'HTTP_CODE' => $http_code,
            ];
        }
        //Close request
        curl_close($curl);
        return $result;
    }
}

In addition to requesting other people’s interface data. You can also pull files generated by others. For example, someone else’s URL ishttp://47.97.185.90:8060/demo…, pass the returned content result [‘http_body ‘] through file_ put_ Contents ($file_name, result [‘http_body ‘]) can be written to its corresponding directory.

This article is created by Ye Yuwen suzuhara. You don’t need to contact me for reprint, but please indicate the source of the article. Article source: the thought of hearing the bell in the night rain(https://segmentfault.com/u/ye…)