I am back with a new blog post titled “Using cURL with PHP”. cURL is a tool which we can use to send some content or read content from websites, like we do using our browser. We can automate everything we do on the Internet using a web browser using cURL. For demonstration I will use PHP.
If you just want to fetch the content of a URL , we can simply use this;-
$data = file_get_contents('http://www.jellyfishtechnologies.com'); echo $data;
But if you want to make a post request, we have to use cURL. With cURL, we can do the following:
GET Request using cURL:-
<?php $curlRequest = curl_init(); curl_setopt($curlRequest, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curlRequest, CURLOPT_URL, 'https://jellyfishtechnologies.com/blog'); $response = curl_exec($curlRequest); curl_close($curlRequest); echo $response; ?>
The first line initializes the curl request.
As per the PHP documentation. “Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL to return the actual content and not just a boolean value”
curl_exec method actually executes the request and returns the response in the $response variable.
The above example explains how to execute a get request but if we want to execute a POST request we have to set the CURLOPT_POST variable to 1 and send some parameters using an associative array.
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.jft.com/"); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POST, 1); $data = array( 'username' => 'vivek.sadh', 'password' => 'jft' ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); $contents = curl_exec($ch); curl_close($ch);
In the above example we are specifying the parameters we want to send as key/value pair and set it using:-
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
That was all about cURL.