Created
May 30, 2017 10:28
-
-
Save vishalbasnet23/2b389e0410b456545800391fe9ff6276 to your computer and use it in GitHub Desktop.
Generic Curl Call PHP
This file contains hidden or 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
<?php | |
function call($url,$data=array()) { | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
// set custom headers | |
$headers = array('Accept: application/json'); | |
$headers[] = "X-Forwarded-For: {$_SERVER['REMOTE_ADDR']}"; | |
if($access_cred['access_token']) { | |
$headers[] = "Authorization: BEARER {$access_cred['access_token']}"; | |
} | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); | |
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); | |
curl_setopt($ch, CURLOPT_TIMEOUT, '30'); | |
if($data) { | |
curl_setopt($ch, CURLOPT_POST, true); | |
if(is_array($data)) { | |
// needs to encode to support assocative arrays | |
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); | |
} else { | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); | |
} | |
} else { | |
curl_setopt($ch, CURLOPT_HTTPGET, true); | |
} | |
if($response = curl_exec($ch)) { | |
$response = json_decode($response,true); | |
if($error = json_last_error()) { | |
$this->error = array('json'=>$error); | |
} else { | |
return $response; | |
} | |
} else { | |
$this->error = array('curl'=>curl_error($ch)); | |
} | |
} | |
//call('url') //with GET | |
//call('url', $data_params) //with POST |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment