Created
April 28, 2019 17:26
-
-
Save UchePhilz/fb4931bf3054c3501bbb1c628d6d6a00 to your computer and use it in GitHub Desktop.
Curl GET and Curl Post function to consume endpoints (YII2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static function curlPost($arr, $url, $type) { | |
$curl = curl_init(); | |
curl_setopt_array($curl, array( | |
CURLOPT_URL => $url, | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_ENCODING => "", | |
CURLOPT_MAXREDIRS => 10, | |
CURLOPT_TIMEOUT => 30, | |
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, | |
CURLOPT_CUSTOMREQUEST => "POST", | |
CURLOPT_POSTFIELDS => json_encode($arr), | |
CURLOPT_HTTPHEADER => Misc::headerType($type), | |
)); | |
$response = curl_exec($curl); | |
$err = curl_error($curl); | |
curl_close($curl); | |
if ($err) { | |
Yii::error("cURL Error #:" . $err); | |
return null; | |
} else { | |
return $response; | |
} | |
} | |
public static function curlGet($url, $type) { | |
$curl = curl_init(); | |
curl_setopt_array($curl, array( | |
CURLOPT_URL => $url, | |
CURLOPT_RETURNTRANSFER => true, | |
CURLOPT_ENCODING => "", | |
CURLOPT_MAXREDIRS => 10, | |
CURLOPT_TIMEOUT => 30, | |
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, | |
CURLOPT_CUSTOMREQUEST => "GET", | |
CURLOPT_HTTPHEADER => Misc::headerType($type), | |
)); | |
$response = curl_exec($curl); | |
$err = curl_error($curl); | |
curl_close($curl); | |
if ($err) { | |
Yii::error($err); | |
return "cURL Error #:" . $err; | |
} else { | |
return json_decode($response); | |
} | |
} | |
private static function headerType($type) { | |
$header = array(); | |
switch ($type) { | |
case 'endpoint_type': { | |
$header = array( | |
"content-type: application/json" | |
); | |
break; | |
} | |
default : { | |
$header = array("content-type: application/json"); | |
break; | |
} | |
} | |
return $header; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment