What is cURL In PHP and How to Use cURL In PHP
Posted By : Satyam Sharma | 22-Sep-2019
In this blog, we are going to understand the concept of cURL in PHP. There is a library in PHP created by Daniel Stenberg, allows you to connect with many different types of web services called API. This library has the ability to connect with many kinds of protocol like HTTP, HTTPS, FTP, gopher, etc. It supports HTTP POST, PUT, Update, Delete etc kind of request.
cUrl is basically a module which uses this PHP library for makes an HTTP request and gets the response data from the server. We can also make Http request without curl, but for this, you have to change some configuration in php.ini file
Here below the workflow of cUrl, how it works :
1. Initialize curl session.
2. Set different option for the session.
4. Closed Session.
Now, let's go through with each point and understand them deeply.
In step one, We have to initialize the curl session by using the function curl_init(). This is the first and very necessary step for making a curl request.
After initialization, we have to set some options for the session by using curl_set_opt() method. This part of curl decides that what kind of request we are making like the POST, GET, PUT or DELETE. But here we are going to do a get request for basic understanding because Until you will get a basic understanding you can not make any complex task with it. For further knowledge about this, you can also read from the PHP Manual. Here we are going to append a search term using parameter "q=". We set the option for CURLOPT_RETURNTRANSFER, true will tell curl to return the string instead of print it out.
After setting the options for session we are going to execute the command using curl_exec() method and return the response. We can save the response in a variable and also print that response.
Now our third and final step is to close the connection by using curl_close();
For better understand below I am giving a simple example of cURL get the request to get the google search result.
I hope this gonna be a good example for your better understanding. By the doing practice you can make a complex functionality in which you have to use a web service, in some simple steps of cUrl.