cURL Requests with PHP

cURL allows you to connect and communicate to many different types of servers with many different types of protocols. cURL currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols.It also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.
It’s widely used as a way to send data across websites, including things like API interaction and oAuth.cURL is unrestricted in what it can do, from the basic HTTP request, to the more complex FTP upload or interaction with an authentication enclosed HTTPS site.
In this article i will show you how to use cURL POST and GET Requests.

Basics

Before we can do anything with cURL Request,first of all we have to initialize cURL and we do this by calling this function curl_init(); which returns a cURL resource.This function takes one parameter which is the URL you want to send request to.We will discuss it in the later portion of the post.

Settings

Once we got the cURL resource,we can begin to assign our settings.Below is a list of options which i generally use.

KeyDescription
CURLOPT_URLURL to send request to
CURLOPT_RETURNTRANSFERreturn the transfer as a string of the return value of curl_exec() instead of outputting it out directly
CURLOPT_TIMEOUTMaximum Number of seconds to allow cURL to execute
CURLOPT_USERAGENTThe contents of the “User-Agent: ” header to be used in a HTTP request.
CURLOPT_POSTSend Request as POST
CURLOPT_POSTFIELDSArray of data to POST in request
Note: You can go to http://php.net/manual/en/function.curl-setopt.php for more Setting options
We can set the settings by using curl_setopt() function which takes three parameters,the cURL resource,Setting Key and the Value.
Below is the example showing how to setup a curl setting.In the given example we are sending request to http://cURLTesting.com

$curl = curl_init();
curl_setopt($curl,CURLOPT_URL,"http://cURLTesting.com");

As mentioned, we can set the URL by sending a parameter through when getting the cURL resource:

$curl = curl_init("http://cURLTesting.com");

It is possible to set multiple settings at one time by passing array of settings to the function curl_setopt_array().

$curl = curl_init();
curl_setopt_array($curl, array(
   CURLOPT_URL => "http://cURLTesting.com",
   CURLOPT_RETURNTRANSFER => 1
));

Sending Requests

When all the options are sent, and the request is ready to send, call the curl_exec() method, which will execute the cURL request.This function returns three things.

  1. FALSE if there is an error executing the request
  2. TRUE: If the request executed without error and CURLOPT_RETURNTRANSFER is set to false
  3. The Result: If the request executed without error and CURLOPT_RETURNTRANSFER is set to true
$curl = curl_init();
curl_setopt_array($curl, array(
   CURLOPT_URL => "http://cURLTesting.com",
   CURLOPT_RETURNTRANSFER => 1
));

$result = curl_exec($curl); //Executing the Result

With $result now containing the result from the page which might be JSON, HTML, String.

Close Request

When you have sent the Request and got the result back,you should look to close the cURL to free up some system resources and this can be done by just calling curl_close() function.This function required the cURL resource as a parameter.

curl_close($curl);

GET Request

A GET request is the default request method that is used, and is very straight forward to use, infact all of the examples so far have been GET requests. If you want to send parameters along in the request you simply append them to the URL as a query string such as http://cURLTesting.com/?item1=value&item2=value2.
So for example to send a GET request to the above URL and return the result we would use:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://cURLTesting.com/?item1=value&item2=value2',
    CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT']
));
// Send the request & save response to $resp
$result = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

POST Request

The difference between the POST and GET request syntax is the addition of one setting, two if you want to send some data. We’ll be setting CURLOPT_POST to true and sending an array of data through with the setting CURLOPT_POSTFIELDS.
So for example switching the above GET request to be a POST request, we would use the following code:

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://cURLTesting.com/',
    CURLOPT_USERAGENT => $_SERVER['HTTP_USER_AGENT'],
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => array(
        item1 => 'value',
        item2 => 'value2'
    )
));
// Send the request & save response to $result
$result = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);

There you have a POST request that will work the same as our GET request above and return the response back to the script so that you can use it as you want.

Error Handling

You cannot guarantee that the response will be in the format that you want, or that the site will even be available,then you may face an error.
There are a few functions that you can use to handle errors and they are:

  • curl_error() – returns a string error message, will be blank if the request doesn’t fail.
  • curl_errno() – which will return the cURL error number which you can then look up on this page listing error codes.

Below is an Example.

if(!curl_exec($curl)){
    die('Error: "' . curl_error($curl) . '" - Code: ' . curl_errno($curl));
}

You might want to look at using the setting CURLOPT_FAILONERROR as true if you want any HTTP response code greater than 400 to cause an error, instead of returning the page HTML.

The END

cURL is a behemoth, and has many many possibilities. Some sites might only serve pages to some user agents, and when working with APIs, some might request you send a specfici user agent, this is something to be aware of.

Don’t forget to share this page and if you wants to get updates of such like posts then subscribe us.

Shubham Kumar

Hey, I am Shubham and i love Blogging, Coding and exploring new things and obviously sharing my experience with you.

You may also like...

Leave a Reply

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