php http_post 模拟(GET|POST|DELETE|PUT)提交相关函数分享

php http_post 模拟(GET|POST|DELETE|PUT)提交相关函数分享

Tony哥
2019-11-15 / 0 评论 / 177 阅读 / 正在检测是否收录...
if (!function_exists('http_post')) {
    /**
     * * 模拟提交数据
     * @param $url
     * @param string $data      null|string|jsonString|array|object
     * @param string $method    GET|POST|DELETE|PUT
     * @param string $type      json|form-data
     * @param array $header     array_header
     * @return bool|string
     */
    function http_post($url,$data="",$method = 'POST',$type='json',$header=[])
    {
        //初始化
        $ch = curl_init();
        $headers = [
            'form-data' => ['Content-Type: multipart/form-data'],
            'json'      => ['Content-Type: application/json'],
        ];

        function toData(&$arr){
            $post=[];
            foreach ($arr AS $key=>$value){
                array_push($post,"{$key}=".urlencode($value));
            }
            $arr = join('&',$post);
        }

        $Header=[];
        if(!$data) $method='GET';
        if($method == 'GET'){
            if($data){
                if(is_array($data)||is_object($data)) toData($data);
                $querystring = http_build_query($data);
                $url = $url.(strpos($url,'?') !== false?'&':'?').$querystring;
            }
        }else{
            if(is_array($data)||is_object($data)){
                $type='form-data';
                toData($data);
            }
            isset($headers[$type]) && $Header=$headers[$type];
        }

        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);         // 执行后不直接打印出来
        if($method == 'POST'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');     // 请求方式
            curl_setopt($ch, CURLOPT_POST, true);               // post提交
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);              // post的变量
        }
        if($method == 'PUT'){
            curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        }
        if($method == 'DELETE'){
            curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
            curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
        }
        if(stripos($url,"https://")!==FALSE){
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 不从证书中检查SSL加密算法是否存在
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, array_merge($Header,$header));
        $output = curl_exec($ch); //执行并获取HTML文档内容
        $aStatus = curl_getinfo($ch);
        curl_close($ch);
        if(intval($aStatus["http_code"])==200){
            return $output;
        }else{
            return false;
        }
    }
}
0

评论 (0)

取消