Sending GET and POST requests in PHP using CURL

leroykayanda - Feb 26 '22 - - Dev Community

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
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player