php post 设置header json传参

2020-04-28  本文已影响0人  第五季资源

public function urlGetContent(url,params = null, method = 'GET',json = false)
{
ch = curl_init(); curl_setopt(ch, CURLOPT_URL, url); curl_setopt(ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt(ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt(ch, CURLOPT_HEADER, 0);

    if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($json && is_array($params)) {
            $params = json_encode($params);
        }
        if (is_string($params) || is_array($params)) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        } else {
            // error_log("Argument \$params should be an array of parameters or (if you want to send raw data) a string");
            return false;
        }

        if ($json) { //发送JSON数据
            curl_setopt($ch, CURLOPT_HTTPHEADER,
                array(
                    'Content-Type: application/json; charset=utf-8',
                    'Content-Length:' . strlen($params),
                  
        }
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}
上一篇 下一篇

猜你喜欢

热点阅读