PHP cURL Examples: 10 Awesome Things to Do With cURL



New to cURL? If yes, check out the following articles to learn the purposes and basics of cURL/libcurl.

Please note that some of the techniques shown here can be used for “blackhat” methods. The goal of this article is only educationnal, please do not use any of the snippets below for illegal stuff.

1 – Update your Facebook status

Wanna update your facebook status, but don’t want to go to, login, and finally being able to update your status? Simply save the following code on your server, define the variables, and voilà !

<?PHP /******************************* *	Facebook Status Updater *	Christian Flickinger * *	April 20, 2007 *******************************/  $status = 'YOUR_STATUS'; $first_name = 'YOUR_FIRST_NAME'; $login_email = 'YOUR_LOGIN_EMAIL'; $login_pass = 'YOUR_PASSWORD';  $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, ';'); curl_setopt($ch, CURLOPT_POSTFIELDS,'email='.urlencode($login_email).'&pass='.urlencode($login_pass).'&login=Login'); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_COOKIEJAR, "my_cookies.txt"); curl_setopt($ch, CURLOPT_COOKIEFILE, "my_cookies.txt"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv: Gecko/20070309 Firefox/"); curl_exec($ch);  curl_setopt($ch, CURLOPT_POST, 0); curl_setopt($ch, CURLOPT_URL, ''); $page = curl_exec($ch);  curl_setopt($ch, CURLOPT_POST, 1); preg_match('/name="post_form_id" value="(.*)" />'.ucfirst($first_name).'/', $page, $form_id); curl_setopt($ch, CURLOPT_POSTFIELDS,'post_form_id='.$form_id[1].'&status='.urlencode($status).'&update=Update'); curl_setopt($ch, CURLOPT_URL, ''); curl_exec($ch); ?>

2 – Get download speed of your webserver

Do you ever wanted to know the exact download speed of your webserver (or any other?) If yes, you’ll love that code. You just have to initialize the $url variable with any resources from the webserver (images, pdf, etc), place the file on your server and point your browser to it. The output will be a full report of download speed.

<?php error_reporting(E_ALL | E_STRICT);   // Initialize cURL with given url $url = ''; $ch = curl_init($url);   curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_USERAGENT, 'Sitepoint Examples (thread 581410;'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($ch, CURLOPT_TIMEOUT, 60);   set_time_limit(65);   $execute = curl_exec($ch); $info = curl_getinfo($ch);   // Time spent downloading, I think $time = $info['total_time']        - $info['namelookup_time']        - $info['connect_time']        - $info['pretransfer_time']        - $info['starttransfer_time']        - $info['redirect_time'];     // Echo friendly messages header('Content-Type: text/plain'); printf("Downloaded %d bytes in %0.4f seconds.n", $info['size_download'], $time); printf("Which is %0.4f mbpsn", $info['size_download'] * 8 / $time / 1024 / 1024); printf("CURL said %0.4f mbpsn", $info['speed_download'] * 8 / 1024 / 1024);   echo "nncurl_getinfo() said:n", str_repeat('-', 31 + strlen($url)), "n"; foreach ($info as $label => $value) { 	printf("%-30s %sn", $label, $value); } ?>


3 – Myspace login using cURL

<?php  function login( $data, $useragent = 'Mozilla 4.01', $proxy = false ) {     $ch = curl_init();     $hash = crc32( $data['email'].$data['pass'] );     $hash = sprintf( "%u", $hash );     $randnum = $hash.rand( 0, 9999999 );     if( $proxy ) curl_setopt( $ch, CURLOPT_PROXY, $proxy );     curl_setopt( $ch, CURLOPT_COOKIEJAR, '/tmp/cookiejar-'.$randnum );     curl_setopt( $ch, CURLOPT_COOKIEFILE, '/tmp/cookiejar-'.$randnum );     curl_setopt( $ch, CURLOPT_USERAGENT, $useragent );     curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, 1 );     curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );     curl_setopt( $ch, CURLOPT_POST, 0);     curl_setopt( $ch, CURLOPT_URL, '' );     $page = curl_exec( $ch );     preg_match( '/MyToken=(.+?)"/i', $page, $token );     if( $token[1] ) {         curl_setopt( $ch, CURLOPT_URL, ''.$token[1] );         curl_setopt( $ch, CURLOPT_REFERER, '' );         curl_setopt( $ch, CURLOPT_HTTPHEADER, Array( 'Content-Type: application/x-www-form-urlencoded' ) );         curl_setopt( $ch, CURLOPT_POST, 1 );         $postfields = 'NextPage=&email='.urlencode( $data['mail'] ).'&password='.urlencode( $data['pass'] ).'&loginbutton.x=&loginbutton.y=';         curl_setopt( $ch, CURLOPT_POSTFIELDS, $postfields );         $page = curl_exec( $ch );         if( strpos( $page, 'SignOut' ) !== false ) {                 return $randnum;         }         else {             preg_match( '/MyToken=(.+?)"/i', $page, $token );             preg_match( '/replace("([^"]+)"/', $page, $redirpage );             if( $token[1] ) {                 curl_setopt( $ch, CURLOPT_POST, 0 );                 curl_setopt( $ch, CURLOPT_URL, ''.$token[1] );                 $page = curl_exec( $ch );                 curl_close( $ch );                 if( strpos( $page, 'SignOut' ) !== false ) {                     return $randnum;                 }             }             elseif( $redirpage[1] ) {                 curl_setopt( $ch, CURLOPT_REFERER, ''.$token[1] );                 curl_setopt( $ch, CURLOPT_URL, $redirpage[1] );                 curl_setopt( $ch, CURLOPT_POST, 0 );                 $page = curl_exec( $ch );                 curl_close( $ch );                 if( strpos( $page, 'SignOut' ) !== false ) {                     return $randnum;                 }             }         }     }     return false; } ?>


4 – Publish a post on your WordPress blog, using cURL

This function can post on your WordPress blog. You don’t need to login to your WP dashboard etc.
Though, you must activate the XMLRPC posting option in your WordPress blog. If this option isn’t activated, the code will not be able to insert anything into WordPress database. Another thing, make sure the XMLRPC functions are activated on your php.ini file.

function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') {     $title = htmlentities($title,ENT_NOQUOTES,$encoding);     $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding);           $content = array(         'title'=>$title,         'description'=>$body,         'mt_allow_comments'=>0,  // 1 to allow comments         'mt_allow_pings'=>0,  // 1 to allow trackbacks         'post_type'=>'post',         'mt_keywords'=>$keywords,         'categories'=>array($category)     );     $params = array(0,$username,$password,$content,true);     $request = xmlrpc_encode_request('metaWeblog.newPost',$params);     $ch = curl_init();     curl_setopt($ch, CURLOPT_POSTFIELDS, $request);     curl_setopt($ch, CURLOPT_URL, $rpcurl);     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     curl_setopt($ch, CURLOPT_TIMEOUT, 1);     $results = curl_exec($ch);     curl_close($ch);     return $results;  ?>

5 – Test the existence of a given url

I know, it sounds basic. In fact, it is basic, but it is also very useful, especially when you have to work with external resources.

<?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, ""); curl_setopt($ch, CURLOPT_HEADER, true); curl_setopt($ch, CURLOPT_NOBODY, true); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $data = curl_exec($ch); curl_close($ch) echo $data; ?>


In a previous article, I have discussed how spammers spams your WordPress blog. To do so, they simply have to fill the $postfields array with the info they want to display and load the page.
Of course, this code is only for educationnal purposes.

<?php $postfields = array(); $postfields["action"] = "submit"; $postfields["author"] = "Spammer"; $postfields["email"] = "[email protected]"; $postfields["url"] = ""; $postfields["comment"] = "I am a stupid spammer."; $postfields["comment_post_ID"] = "123"; $postfields["_wp_unfiltered_html_comment"] = "0d870b294b"; //Url of the form submission $url = ""; $useragent = "Mozilla/5.0"; $referer = $url;   //Initialize CURL session $ch = curl_init($url); //CURL options curl_setopt($ch, CURLOPT_POST, 1); //We post $postfields data curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); //We define an useragent (Mozilla/5.0) curl_setopt($ch, CURLOPT_USERAGENT, $useragent); //We define a refferer ($url) curl_setopt($ch, CURLOPT_REFERER, $referer); //We get the result page in a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //We exits CURL $result = curl_exec($ch); curl_close($ch);  //Finally, we display the result echo $result; ?>

7 – Follow your Adsense earnings with an RSS reader

Most bloggers uses Adsense on their blog and (try to) make money with Google. This excellent snippet allows you to follow your Adsense earnings…with a RSS reader! Definitely awesome.
(Script too big to be displayed on the blog, click here to preview)

8 – Get feed subscribers count in full text

If you’re a blogger, you’re probably using the popular FeedBurner service, which allo you to know how many people grabbed your rss feed. Feedburner have a chicklet to proudly display your subscriber count on your blog. I personally like the chicklet’s look, but I heard lots of bloggers complaining about it. happilly, cURL can simply grab the count value and return it to you as a variable so you can display it as you want on your blog.

//get cool feedburner count $whaturl="";  //Initialize the Curl session $ch = curl_init();  //Set curl to return the data instead of printing it to the browser. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  //Set the URL curl_setopt($ch, CURLOPT_URL, $whaturl);  //Execute the fetch $data = curl_exec($ch);  //Close the connection curl_close($ch); $xml = new SimpleXMLElement($data); $fb = $xml->feed->entry['circulation']; //end get cool feedburner count


9 – Get the content of a webpage into a PHP variable

This is a very basic thing to do with cURL, but with endless possibilities. Once you have a webpage in a PHP variable, you can for example, retrieve a particular information on the page to use on your own website.

<?php     ch = curl_init();     curl_setopt($ch, CURLOPT_URL, "");     curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);     $output = curl_exec($ch);     curl_close($ch);      ?>

10 – Post to Twitter using PHP and cURL

Twitter is very popular since some time now, and you probably already have an account there. (We have one too) So, what about using cURL to tweet from your server without connectiong to Twitter?

<?php // Set username and password $username = 'username'; $password = 'password'; // The message you want to send $message = 'is twittering from php using curl'; // The twitter API address $url = ''; // Alternative JSON version // $url = ''; // Set up and execute the curl process $curl_handle = curl_init(); curl_setopt($curl_handle, CURLOPT_URL, "$url"); curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2); curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl_handle, CURLOPT_POST, 1); curl_setopt($curl_handle, CURLOPT_POSTFIELDS, "status=$message"); curl_setopt($curl_handle, CURLOPT_USERPWD, "$username:$password"); $buffer = curl_exec($curl_handle); curl_close($curl_handle); // check for success or failure if (empty($buffer)) {     echo 'message'; } else {     echo 'success'; } ?>


Original Article

More to explore

Receive the latest news

Subscribe To Our Dyno Newsletter

Get notified about new articles. 

Subscribe To Our Dyno Newsletter​

Get notified about new articles.