PHP Making Requests With CURL

PHP Code Snippets Making Requests With CURL


In this code snippet, we’ll see how to send HTTP requests with curl in PHP.

Curl can be used to make HTTP request from the backend in PHP. In this desmonstration we’ll make a POST request to a test API.

Note: Curl documentation here.

Let’s see the example below.



//Set url.
$url = "";
$requestDataObject = [ "title" => "foo", "body" => "bar", "userId" => 1 ];
//Serialize object to json.
$data = json_encode($requestDataObject);

//Initialize curl.
$curl = curl_init($url);
//Setting method type(POST, GET, ...).
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");      
//If PSOT type you can set the body data like this:                                                               
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);     
//If request is successful return the response instead of "true".                                                       
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);   
//Add headers.                                                                                                                              
curl_setopt($curl, CURLOPT_HTTPHEADER, array(                                                                          
    'Content-Type: application/json',                                                                                
    'Content-Length: ' . strlen($data))                                                                       

//Make the request.
$response = curl_exec($curl);

//In this case the response will be a json string so we'll use json_decode() to deserialize it.
$jsonResponse = json_decode($response, true); 

//Show response.
echo print_r($jsonResponse);

Resulting output:


Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger