PHP语言curl请求

/**
 * curl请求
 * @param string $url
 * @param array $fields
 * @param bool $is_post
 * @param bool $is_json
 * @return mixed
 */
function request($url, $fields = array(), $is_post = false, $is_json = false)
{
    $cl = curl_init();

    if ($is_post) {
        curl_setopt($cl, CURLOPT_POST, true);
        if (!empty($fields)) {
            if (is_array($fields) || is_object($fields)) {
                $skip = false;
                foreach ($fields as $key => $value) {
                    // POST文件时(instanceof \CurlFile),跳过http_build_query
                    if ($value instanceof \CurlFile) {
                        $skip = true;
                    }
                }
                if (!$skip) {
                    $fields = http_build_query($fields);
                }
            }
            curl_setopt($cl, CURLOPT_POSTFIELDS, $fields);
        }
    } else {
        if (!empty($fields)) {
            $url = $url.(strpos($url, '?') === false ? '?' : '&').http_build_query($fields);
        }
        curl_setopt($cl, CURLOPT_HTTPGET, true);
    }

    curl_setopt($cl, CURLOPT_URL, $url);
    if (stripos($url, 'https://') === 0) {
        curl_setopt($cl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($cl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($cl, CURLOPT_SSLVERSION, 1);
    }
    curl_setopt($cl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($cl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36');
    curl_setopt($cl, CURLOPT_HTTPHEADER, array('Accept-Language: zh-CN,zh;q=0.9'));
    curl_setopt($cl, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($cl, CURLOPT_TIMEOUT, 60);
    $response = curl_exec($cl);
    $status = curl_getinfo($cl);
    curl_close($cl);
    if (isset($status['http_code']) && $status['http_code'] == 200) {
        if ($is_json) {
            $response = json_decode($response, true);
        }
        return $response;
    } else {
        return false;
    }
}
最后修改:2020 年 07 月 01 日 06 : 20 PM
如果觉得我的文章对你有用,请随意赞赏

发表评论