PHP and cURL snippets

cURL, and its PHP extension libcURL, are very useful tools for tasks like simulating a web browser, submit forms or login to a web service. In this article, I’m going to show you some amazing things that you can do using PHP and cURL.


Check if a specific website is available

Want to know if a specific website is available? cURL is here to help. This script can be used with a cron job to monitor your websites.

Don’t forget to update the script with the url you want to check on line 3. Once done, just paste it somewhere and it will let you know about the site availability.


       if (isDomainAvailible(''))
               echo "Up and running!";
               echo "Woops, nothing found there.";

       //returns true, if domain is availible, false if not
       function isDomainAvailible($domain)
               //check, if a valid url is provided
               if(!filter_var($domain, FILTER_VALIDATE_URL))
                       return false;

               //initialize curl
               $curlInit = curl_init($domain);

               //get answer
               $response = curl_exec($curlInit);


               if ($response) return true;

               return false;

→ Source:

cURL replacement for file_get_contents()

The file_get_contents() function is very useful but it is unfortunely deactivated by default on some webhosts. Using cURL, we can write a replacement function that works exactly like file_get_contents().

function file_get_contents_curl($url) {
	$ch = curl_init();

	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
	curl_setopt($ch, CURLOPT_URL, $url);

	$data = curl_exec($ch);

	return $data;

→ Source:

Get latest Twitter status

Using PHP and cURL, it is pretty easy to get the status of a specific user. Once you have it, what about displaying it on your blog, like I do in WPRecipes footer?

function get_status($twitter_id, $hyperlinks = true) {
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, "$twitter_id.xml?count=1");
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    $src = curl_exec($c);
    preg_match('/<text>(.*)<\/text>/', $src, $m);
    $status = htmlentities($m[1]);
    if( $hyperlinks ) $status = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", '<a href="%5C%22%5C%5C0%5C%22">\\0</a>', $status);

The function is super easy to use:

echo get_status('catswhocode');

→ Source:

Twitter: test friendship between two users

If you want to know if a specific user is following you (or someone else) you have to use the Twitter API. This snippet will echo true if the two users specified on lines 18 and 19 are friends. It will return false otherwise.

function make_request($url) {
	$ch = curl_init();
	$result = curl_exec($ch);
	return $result;

/* gets the match */
function get_match($regex,$content) {
	return $matches[1];

/* persons to test */
$person1 = 'phpsnippets';
$person2 = 'catswhocode';

/* send request to twitter */
$url = '';
$format = 'xml';

/* check */
$persons12 = make_request($url.'.'.$format.'?user_a='.$person1.'&user_b='.$person2);
$result = get_match('/<friends>(.*)<\/friends>/isU',$persons12);
echo $result; // returns "true" or "false"

→ Source:

Download and save images from a page using cURL

Here is a set of functions that can be very useful: Give this script the url of a webpage, and it will save all images from this page on your server.

function getImages($html) {
    $matches = array();
    $regex = '~*?)\.jpg~i';
    preg_match_all($regex, $html, $matches);
    foreach ($matches[1] as $img) {

function saveImg($name) {
    $url = ''.$name.'.jpg';
    $data = get_data($url);
    file_put_contents('photos/'.$name.'.jpg', $data);

$i = 1;
$l = 101;

while ($i < $l) {
    $html = get_data(''.$i.'/');
    $i += 1;

→ Source:

Convert currencies using cURl and Google

Converting currencies isn’t very hard to do, but as the currencies fluctuates all the time, we definitely need to use a service like Google to get the most recent values. The currency() function take 3 parameters: from, to, and sum.

function currency($from_Currency,$to_Currency,$amount) {
    $amount = urlencode($amount);
    $from_Currency = urlencode($from_Currency);
    $to_Currency = urlencode($to_Currency);
    $url = "$amount$from_Currency=?$to_Currency";
    $ch = curl_init();
    $timeout = 0;
    curl_setopt ($ch, CURLOPT_URL, $url);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,  CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $rawdata = curl_exec($ch);
    $data = explode('"', $rawdata);
    $data = explode(' ', $data['3']);
    $var = $data['0'];
    return round($var,2);

→ Source:

Get remote filesize using cURL

Want to be able to calculate the size of a specific file? The following function can help. It takes 3 parameters: the file url, and in case the file is password protected, a username and a password.

function remote_filesize($url, $user = "", $pw = ""){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);

    if(!empty($user) && !empty($pw))
        $headers = array('Authorization: Basic ' .  base64_encode("$user:$pw"));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

    $ok = curl_exec($ch);
    $head = ob_get_contents();

    $regex = '/Content-Length:\s([0-9].+?)\s/';
    $count = preg_match($regex, $head, $matches);

    return isset($matches[1]) ? $matches[1] : "unknown";

→ Source:

FTP upload with cURL

PHP does have a FTP library, but you can also use cURL to upload files on a FTP server. Here is a working example:

// open a file pointer
$file = fopen("/path/to/file", "r");

// the url contains most of the info needed
$url = "";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// upload related options
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize("/path/to/file"));

// set for ASCII mode (e.g. text files)
curl_setopt($ch, CURLOPT_FTPASCII, 1);

$output = curl_exec($ch);

→ Source:

Leave a comment