php post请求封装Authorization验证

180it 2021-05-13 PM 1131℃ 0条
function http_get($url, $param = array())
{
    if (!is_array($param)) {
        throw new Exception("参数必须为array");
    }
    $p = '';
    foreach ($param as $key => $value) {
        $p = $p . $key . '=' . $value . '&';
    }
    if (preg_match('/\?[\d\D]+/', $url)) {//matched ?c
        $p = '&' . $p;
    } else if (preg_match('/\?$/', $url)) {//matched ?$
        $p = $p;
    } else {
        $p = '?' . $p;
    }
    $p = preg_replace('/&$/', '', $p);
    $url = $url . $p;

    $httph = curl_init($url);
    curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($httph, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
    curl_setopt($httph, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($httph, CURLOPT_HEADER, 1);
    $rst = curl_exec($httph);
    curl_close($httph);
    return $rst;
}

function http_post($url, $param, $appid = null, $appsecret = null)
{

    // if(!is_array($param)){
    //     throw new Exception("参数必须为array");
    // }
    $httph = curl_init($url);
    curl_setopt($httph, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($httph, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($httph, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($httph, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");

    // 需要通过Authorization验证
    if (!empty($appid) && !empty($appsecret)) {

        $author = base64_encode($appid . ':' . $appsecret);

        $headers[] = 'Accept:application/json';

        $headers[] = 'Authorization: Basic ' . $author;

        curl_setopt($httph, CURLOPT_HTTPHEADER, $headers);
    }
    curl_setopt($httph, CURLOPT_POST, 1);//设置为POST方式
    curl_setopt($httph, CURLOPT_POSTFIELDS, $param);

    curl_setopt($httph, CURLOPT_CONNECTTIMEOUT, 3);//设置超时时间
    $rst = curl_exec($httph);
    //检查是否404(网页找不到)
    $httpCode = curl_getinfo($httph, CURLINFO_HTTP_CODE);
    // var_dump($httpCode);
    if ($httpCode == 404) {
        return false;
    } else {
        return $rst;
    }
    curl_close($httph);
}

————————————————

原文链接:https://blog.csdn.net/weixin_44452446/article/details/107354688

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

php post请求封装Authorization验证