Getting HTTP code in PHP using curl

后端 未结 9 2140
无人共我
无人共我 2020-11-28 03:43

I\'m using CURL to get the status of a site, if it\'s up/down or redirecting to another site. I want to get it as streamlined as possible, but it\'s not working well.

<
9条回答
  •  情话喂你
    2020-11-28 03:52

    use this hitCurl method for fetch all type of api response i.e. Get / Post

            function hitCurl($url,$param = [],$type = 'POST'){
            $ch = curl_init();
            if(strtoupper($type) == 'GET'){
                $param = http_build_query((array)$param);
                $url = "{$url}?{$param}";
            }else{
                curl_setopt_array($ch,[
                    CURLOPT_POST => (strtoupper($type) == 'POST'),
                    CURLOPT_POSTFIELDS => (array)$param,
                ]);
            }
            curl_setopt_array($ch,[
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
            ]);
            $resp = curl_exec($ch);
            $statusCode = curl_getinfo($ch,CURLINFO_HTTP_CODE);
            curl_close($ch);
            return [
                'statusCode' => $statusCode,
                'resp' => $resp
            ];
        }
    

    Demo function to test api

     function fetchApiData(){
            $url = 'https://postman-echo.com/get';
            $resp = $this->hitCurl($url,[
                'foo1'=>'bar1',
                'foo2'=>'bar2'
            ],'get');
            $apiData = "Getting header code {$resp['statusCode']}";
            if($resp['statusCode'] == 200){
                $apiData = json_decode($resp['resp']);
            }
            echo "
    ";
            print_r ($apiData);
            echo "
    "; }

提交回复
热议问题