DEV Community

leroykayanda
leroykayanda

Posted on

Sending GET and POST requests in PHP using CURL

GET

<?php
$url = "https://example.com";
$AccessKey = "123";

//initialize curl
$curl = curl_init();

//set the url
curl_setopt($curl, CURLOPT_URL, $url);

//setting custom headers
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json', 'AccessKey: $AccessKey'));

//return the results as a string rather than printing them on the screen
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

//send the request
$curl_response = curl_exec($curl);
var_dump($curl_response);

//if result is a JSON, convert it into an array
$res = json_decode($curl_response, true);
var_dump($res);
Enter fullscreen mode Exit fullscreen mode

POST

$AccessKey = "123";

$url = "example.com";

//initialize curl and set url
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);

//set custom headers
curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type:application/json", "AccessKey: $AccessKey"));

//return the results as a string rather than printing them on the screen
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

//enable POST and set POST data
$curl_post_data = array(
    "foo" => 'bar',
);

$data_string = json_encode($curl_post_data);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data_string);

//send the request
$curl_response = curl_exec($curl);
var_dump($curl_response);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
tobecci profile image
Tochukwu Ojinaka • Edited

Thanks for this article.
i do want to add that something is missing, in the post request example, the variable $curl_response contains a string which is a cmbination of the, request info, header and body, my question is,

how does one get the response body alone?.

is there a function for doing so? thanks.

[Edit]
i found a way to do this, but not really confident it would work for all cases

$curl_response = curl_exec($curl);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$response_body = substr($curl_response, $header_size);
Enter fullscreen mode Exit fullscreen mode