Skip to content

Instantly share code, notes, and snippets.

@UchePhilz
Created April 28, 2019 17:26
Show Gist options
  • Save UchePhilz/fb4931bf3054c3501bbb1c628d6d6a00 to your computer and use it in GitHub Desktop.
Save UchePhilz/fb4931bf3054c3501bbb1c628d6d6a00 to your computer and use it in GitHub Desktop.
Curl GET and Curl Post function to consume endpoints (YII2)
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