php发送一个php请求

    function http_curl($url,$method='GET',$data=[]){
        $method = strtoupper($method);
        $headers = [];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        if(isset($data['headers']) && $data['headers']){
            $headers  = $data['headers'];
            unset($data['headers']);
        }else{
            $headers[] = 'Content-Type: application/x-www-form-urlencoded';
            $headers[] = 'Accept: application/json';
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        if($data){
            curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }

        if($method === 'PUT' || $method === 'DELETE'){
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        }elseif($method === 'POST'){
            curl_setopt($ch, CURLOPT_POST, 1);
        }else{
            curl_setopt($ch, CURLOPT_HTTPGET, 1);
        }

        $response = curl_exec($ch);
        curl_close($ch);
        if($response === false) {
            return curl_error($ch);
        }
        return json_decode($response,true);
    }

  

posted @ 2024-03-26 21:15  侠岚歌  阅读(3)  评论(0)    收藏  举报