php-currl

In PHP CURL POST tutorial, I have explained how to send HTTP GET / POST requests with PHP CURL library.

Below are the examples covered in this article.
1) Send HTTP GET Request with CURL
2) Send HTTP POST Requests with CURL
3) Send Random User-Agent in the Requests
4) Handle redirects (HTTP 301,302)
5) Handle Errors.

Why we need PHP CURL ?
To send HTTP GET requests, simply we can use file_get_contents() method.

1
file_get_contens('http://hayageek.com')

But sending POST request and handling errors are not easy with file_get_contents().

 

Sending HTTP requests is very simple with PHP CURL.You need to follow the four steps to send request.

step 1). Initialize CURL session

1
$ch = curl_init();

step 2). Provide options for the CURL session

1
2
3
curl_setopt($ch,CURLOPT_URL,"http://hayageek.com");
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//curl_setopt($ch,CURLOPT_HEADER, true); //if you want headers

CURLOPT_URL -> URL to fetch
CURLOPT_HEADER -> to include the header/not
CURLOPT_RETURNTRANSFER -> if it is set to true, data is returned as string instead of outputting it.

For full list of options, check this PHP Documentation.

step 3). Execute the CURL session

1
$output=curl_exec($ch);

step 4). Close the session

1
curl_close($ch);

Note: You can check whether CURL enabled/not with the following code.

1
2
3
4
5
6
7
if(is_callable('curl_init')){
   echo "Enabled";
}
else
{
   echo "Not enabled";
}

 

1.PHP CURL GET Example

You can use the below code to send GET request.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function httpGet($url)
{
    $ch = curl_init(); 
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//  curl_setopt($ch,CURLOPT_HEADER, false);
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}
echo httpGet("http://hayageek.com");

 

 

You can use the below code to submit form using PHP CURL.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
function httpPost($url,$params)
{
  $postData = '';
   //create name value pairs seperated by &
   foreach($params as $k => $v)
   {
      $postData .= $k . '='.$v.'&';
   }
   rtrim($postData, '&');
    $ch = curl_init(); 
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_POST, count($postData));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);   
    $output=curl_exec($ch);
    curl_close($ch);
    return $output;
}

How to use the function:

1
2
3
4
5
6
7
$params = array(
   "name" => "Ravishanker Kusuma",
   "age" => "32",
   "location" => "India"
);
echo httpPost("http://hayageek.com/examples/php/curl-examples/post.php",$params);

 

3.Send Random User-Agent in the Requests

You can use the below function to get Random User-Agent.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function getRandomUserAgent()
{
    $userAgents=array(
        "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)",
        "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30)",
        "Opera/9.20 (Windows NT 6.0; U; en)",
        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 8.50",
        "Mozilla/4.0 (compatible; MSIE 6.0; MSIE 5.5; Windows NT 5.1) Opera 7.02 [en]",
        "Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; fr; rv:1.7) Gecko/20040624 Firefox/0.9",
        "Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en) AppleWebKit/48 (like Gecko) Safari/48"
    );
    $random = rand(0,count($userAgents)-1);
    return $userAgents[$random];
}

Using CURLOPT_USERAGENT, you can set User-Agent string.

1
curl_setopt($ch,CURLOPT_USERAGENT,getRandomUserAgent());

 

4.Handle redirects (HTTP 301,302)

To handle URL redirects, set CURLOPT_FOLLOWLOCATION to TRUE.Maximum number of redirects can be controlled using CURLOPT_MAXREDIRS.

1
2
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,TRUE);
curl_setopt($ch,CURLOPT_MAXREDIRS,2);//only 2 redirects

 

5.How to handle CURL errors

we can use curl_errno(),curl_error() methods, to get the last errors for the current session.
curl_error($ch) -> returns error as string
curl_errno($ch) -> returns error number
You can use the below code to handle errors.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function httpGetWithErros($url)
{
    $ch = curl_init(); 
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    $output=curl_exec($ch);
    if($output === false)
    {
        echo "Error Number:".curl_errno($ch)."<br>";
        echo "Error String:".curl_error($ch);
    }
    curl_close($ch);
    return $output;
}

For the full list of errors, refer CURL errors

Referencer :  hayageek

Leave a Reply

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