About
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.
Code:
<?php //Set url. $url = "https://jsonplaceholder.typicode.com/posts"; //Make $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);