Skip to content

Instantly share code, notes, and snippets.

@imran-parray
Last active June 24, 2021 07:06
Show Gist options
  • Save imran-parray/1dc6953955bb84d04787a137d29842a6 to your computer and use it in GitHub Desktop.
Save imran-parray/1dc6953955bb84d04787a137d29842a6 to your computer and use it in GitHub Desktop.
How to make Curl GET and POST request using CURL in PHP

HTTP GET

function httpGET($url,$headers)
{
   	$curl = curl_init($url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response);

}

$headers=['Accept: application/json'];
$res=httpGET('https://imxx.requestcatcher.com/',$headers)

HTTP POST with DATA

function httpPost($url, $data,$headers)
{
   	$curl = curl_init($url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($curl);
    curl_close($curl);
    return json_decode($response);

}



$CLEINT_ID='XYZ';
$CLEINT_SECRET='XYZ';
$URL='https://github.com/login/oauth/access_token';


$data=[
'code'=>$code,
'client_id'=>$CLEINT_ID,
'client_secret'=>$CLEINT_SECRET
];

$headers=['Accept: application/json'];

$res=httpPost($URL,$data,$headers);

Adding http_build_query will turn the request to normal POST request Removing http_build_query will convert the request to multiform content-type

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment