In this day and age, there are many ways to transfer data between servers. One of the fastest, most popular, and easiest method is using the cURL library with the ability to work in many protocols, including HTTP, HTTPS, FTP, WebDAV, and more. In order to use this in PHP, you need to install the libcurl package. You must also enable libcurl once it is installed by uncommenting the line in your php.ini configuration file.
To verify that we have cURL installed and enabled, create a new file called phpinfo.php with the following code in it:
Now go into your web browser and open up http://localhost/phpinfo.php or wherever you placed it. Once you are there, just do a search for the cURL module. If it isn’t there, you must be using an older version of libcurl or not enabled it.
For your first script, we will be getting an RSS file from digg. In order to do this, we first need to initiate cURL, set some of our options (including URL), dispatch it, then close it.
In the above code, we use the PHP constant CURLOPT_RETURNTRANSFER, because if we don’t the function curl_exec($ch) will automatically echo the data onto the page. We make sure to enable it so that the data instead goes into the $rss variable so that you may work with it. Another constant we used was CURLOPT_FOLLOWLOCATION, because if one day digg.com decides to change the location of this feed, and has put a redirect in place of it, cURL will transfer itself to this new URL.
Sure you can get data from a page, but you can also send as well! Lets say you want to search for videos on YouTube, you may do so as follows:
If you have already tested the code out, you may have noticed that you see YouTube. This is because I have removed the CURLOPT_RETURNTRANSFER constant just for fun, but you can ofcourse just reinclude it and make sure that curl_exec($ch) is returning the data into a variable. CURLOPT_POST switches cURL’s setting from getting, to sending, while CURLOPT_POSTFIELDS sets the data you want to send. In this case search_query=libcurl
If you go to web sites that have protected directories and your browser requires a username and password, you can also use cURL for that!
This is basically for something called HTTP Authentication where you need an authorized username and password to continue. The PHP cURL constant CURLOPT_USERPWD lets you define the username and password with a colon in between. Everything else is pretty much normal.
Of course you can also use HTTPS (HTTP Secure) and FTP connections and more. You can find more tutorials on PHP here on Devlounge and please comment with your thoughts on the article.