Wednesday, 25 September 2013

What is cURL and how to use cURL in PHP

Introduction

cURL stands for client URL

curl is a command line tool for transferring data with URL syntax, supporting DICT, FILE, FTP, FTPS, Gopher, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, POP3, POP3S, RTMP, RTSP, SCP, SFTP, SMTP, SMTPS, Telnet and TFTP. curl supports SSL certificates, HTTP POST, HTTP PUT, FTP uploading, HTTP form based upload, proxies, cookies, user+password authentication (Basic, Digest, NTLM, Negotiate, kerberos...), file transfer resume, proxy tunneling and a busload of other useful tricks.

PHP cURL allows you to read websites, make automated logins, upload files and many more.

Requirements

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

Example

Now that you know what cURL is, I think it’s time to look at some code.

<?php
$ch = curl_init ("http://www.yahoo.com");//Initialize curl with the URL of yahoo
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
/*Tell php curl that we want the data returned to us instead of being displayed*/ 
 $yahoo = curl_exec ($ch);//Execute curl and put the output in $yahoo.
?>


The power of PHP cURL lies within the curl_setopt() function. This function instructs cURL of what exactly we want to do. Let’s say, what if a webpage that you want to access checks for the HTTP_REFERER header? Or perhaps, what if you need to access a webpage that works correctly only if cookies are enabled? for more parameters of  curl_setopt() click here .

Here’s another example… This time we specify the HTTP_REFERER…

<?php
$ch = curl_init ("http://www.somedomain.com/page2.php");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_REFERER, "http://www.somedomain.com/page1.php");
$page = curl_exec ($ch);
?>



In this example, the CURLOPT_REFERER line tells cURL to set the HTTP_REFERER header to http://www.somedomain.com/page1.php.

PHP cURL can do more. It can send POST data, it can log on to a website and automate tasks as if it was a real person and much more.

No comments:

Post a Comment