28 May, 2010

Download file using curl

Following code sample is used to download file using curl. In this example we download image using curl and
save it to some file in our directory.

// URL to Download Image
$url = "http://www.someurl.com/images/image.jpg";
// Initialize a CURL session.
$ch = curl_init();
// Pass URL as parameter.
curl_setopt($ch, CURLOPT_URL, $url);
// Return contents.in a variable
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Data is in binary format
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//open file in write mode
$file = fopen("somedir/somename.jpg", "w");
//filename that the transfered binary data is returned to
curl_setopt($ch, CURLOPT_FILE, $file);
//Grab the jpg and save the contents in the $data variable
$data = curl_exec($ch);
curl_close($ch); // close curl resource
?>

27 May, 2010

Add Events to Yahoo Calendar Using cURL

We can add events to yahoo calendar using curl or sync our custom php calendar with yahoo calendar using curl.
Yahoo calendar events have various parameters that need to be added in curl request for adding events to yahoo.
I've listed out some of the event parameters that I have known in the following code.
The code first login to yahoo with curl and after successful login it adds events to yahoo calendar.

$serviceUrl = "http://calendar.yahoo.com/";
$authUrl = "http://login.yahoo.com/config/login?";
$userAgent = "YahooSeeker-Testing/v3.9 (compatible; Mozilla 4.0; MSIE 5.5; http://search.yahoo.com/)";
$referer = "http://my.yahoo.com";
$login = "your-yahoo-username";
$password = "your-yahoo-password";
$numPostData = 22;
$cookieFileJar = "cookie.txt";
$cookie = 0;
$postData = "login=$login&passwd=$password&.src=&.tries=5&.bypass=&.partner=&.md5=&.hash=&.intl=us&.tries=1&.challenge=ydKtXwwZarNeRMeAufKa56.oJqaO&.u=dmvmk8p231bpr&.yplus=&.emailCode=&pkg=&stepid=&.ev=&hasMsgr=0&.v=0&.chkP=N&.last=&.done=" . $serviceUrl;

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);

// Set the referrer
curl_setopt($ch, CURLOPT_REFERER, $referer);

// Set the authentication url
curl_setopt($ch, CURLOPT_URL, $authUrl);

// Set number of post fields
curl_setopt($ch, CURLOPT_POST, $numPostData);

//Set post data in key=value pair such as login=yourusername
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

//Set filename for storing cookie information
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileJar);

//Set ffilename for checking the stored cookie information
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);

//Set option for cookie
curl_setopt($ch, CURLOPT_COOKIE, $cookie);

//set this to output the result as string and not output directly ot browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//set this value to 1 if you want to redirect to the url you provided as service url
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

//Set this option if you do not want to verify ssl
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

//set this option if you do not want to verify peer's certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

//now execute the curl
$res = curl_exec($ch);

//check if the username and password is valid
if ((preg_match("/invalid/i", $res)) || (preg_match("/not yet taken/i", $res))) {
echo "Invalid Login";
}
else {
//logged in successfully
//TITLE => Event title
//TYPE => Event Type (10 is for Appointment by default)
//ST => Start date format is YYYYMMDDTHHMMSS
//DUR => Total duration in HHMM format
//DESC => is event description
//in_loc => is event location

//other parameters that can be set are
//in_csz => city/state/zip value
//in_st => street name, can have comma in between names

$date = "20100527T130000";
$title = urlencode("Lunch with Bhupal at KFC");
$loc = urlencode("Kathmandu");
$desc = urlencode("Is test event");
//url for the yahoo calendar event along with event parameters
$url = "http://calendar.yahoo.com/?v=60&ST=". $date . "&TITLE=" . $title . "&VIEW=d&TYPE=10&DUR=0200&DESC=".$desc."&in_loc=".$loc;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileJar);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
//get the crumb from the link
preg_match("/&.crumb=(.*)\"/", $response, $mah);

$crumbs = $mah[1];
//pass crumb value along with event parameters to yahoo caledar event url
$finalUrl = "http://calendar.yahoo.com/?v=60&ST=". $date . "&TITLE=" . $title . "&VIEW=d&TYPE=10&DUR=0200&DESC=".$desc."&in_loc=".$loc."&.crumb=".$crumbs;
curl_setopt($ch, CURLOPT_URL, $finalUrl);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileJar);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
curl_setopt($ch, CURLOPT_COOKIE, $cookie);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$finalResponse = curl_exec($ch);
echo $finalResponse;
}
?>

23 May, 2010

Find number of days remain using php

Sometimes it is required to get number of days remaining from some date. Following code is used to calculate
how many days remain from some date using php.

//get number of days remaining from some date
$inpDate = "2010-06-06";
list($inpYear, $inpMonth, $inpDay) = split("[./-]", $inpDate);
$numOfDaysRemaining = ceil((mktime(0,0,0,$inpMonth, $inpDay, $inpYear) - time())/86400);
echo "Num of days remaining:".$numOfDaysRemaining;
//Similarly how many days remain from current date can also be found by setting current date to $inpDate variable
?>

Calculate age in year, month and days from birthdate using php

Following code can be used to get the age using php. Simple php date functions is be used to calculate age
from birth date using php

//find the age using php
//get the birth date
$inpDate = "1983-12-30";
//seperate the birth date day, month and year
list($inpYear, $inpMonth, $inpDay) = explode("-", $inpDate);
//get number of days in a month using following php function
$numOfDays = cal_days_in_month(CAL_GREGORIAN, $inpMonth, $inpYear);
//check if the day inputted is greater then number of days in month and set appropriately
if($inpDay > $numOfDays) {
$inpDay = $numOfDays;
}
//set month to 12 if greater then 12
if($inpMonth > 12) {
$inpMonth = 12;
}
//get the difference in year
$diffYear = date("Y") - $inpYear;
//get the difference in month
$diffMonth = date("m") - $inpMonth;
//get the day difference
$diffDay = date("d") - $inpDay;
//check if month is less than 0
if($diffMonth < 0) {
$diffYear -= 1;
$diffMonth += 12;
}
//check if the day is less than 0
if($diffDay < 0) {
$diffMonth -= 1;
$diffDay += $numOfDays;
}
echo "
";
echo $diffYear. "years";
echo "
";
echo $diffMonth." months";
echo "
";
echo $diffDay." days";
?>

22 May, 2010

Get trends in twitter using curl

Following code is used to get current trends in twitter using curl. Its quite simple. Getting current trends from twitter
requires no authentication, so we jost use curl with the trends url provided by twitter api. The response is
json format, and we process the response to display all the trends as links to the trends. It returns top 10 trends
of twitter.

//get the trends url with result as json format
$url = "http://search.twitter.com/trends/current.json";
//initialize the curl with trends url
$ch = curl_init($url);
//set option to return result as string to process it
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute curl
$resp = curl_exec($ch);
//use json_decode of php to decode the json format response
$trends = json_decode($resp, true);
//get the date set as key in trends
$key = key($trends["trends"]);
//set the array
$trendsArr = $trends["trends"][$key];
foreach($trendsArr as $key => $value) {
//$value is an array with keys name and query, query is used in a href link and name displayed as trend name as follows
echo "".$value["name"]."
";
}
?>

Send Tweets to twitter using curl

Its quite easy to post message i.e. tweets to twitter using curl in php. Following code is used to
post tweet to twitter using curl in php.

//add tweet to the twitter using curl in php
$login = "twitterusename"; //twitter username
$passwd = "twitterpassword"; //twitter password
//url for posting status i.e. message
$url = "http://www.twitter.com/statuses/update.xml";
//message to ne posted
$status = "Test Tweet";
//initialize the curl
$ch = curl_init();
//set url for posting message
curl_setopt($ch, CURLOPT_URL, "$url");
//return the response as string so that it can be displayed
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//set the option to curl to indicate we are doing POST
curl_setopt($ch, CURLOPT_POST, 1);
//set the fields for POST
curl_setopt($ch, CURLOPT_POSTFIELDS, "status=$status");
//provide password and username for logging in
curl_setopt($ch, CURLOPT_USERPWD, "$login:$passwd");
//execute the curl
$response = curl_exec($ch);
//get the http code to check for status success or failure
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//check the http code returned in the response
//if code is 200 then succeed else error
if($httpCode == 200) {
echo "Tweet posted successfully.";
}
else {
echo "Some error occured while posting the tweet.";
}
?>

21 May, 2010

Get Most Viewed YouTube Videos Using PHP

The following code is used to get most viewed youtube videos using php. I've used simplexml for
processing the response that we get from the youtube feed url for most vewed youtube videos.
I then go through each of the entry element of response using foreach method. The code provides details cush as
author name, length of video, total views, favorites count, thumbnial image, url of the video, etc.

//code to get most viewed videos using php with youtube api
//the feed url for most viewed youtube videos
$url = 'http://gdata.youtube.com/feeds/api/standardfeeds/most_viewed';
$xml = simplexml_load_file($url);
//the entry tag of most viewed videos in youtube contains video name, title, category, description, etc kind of information
foreach($xml->entry as $item) {
//nodes inside media; the media rss url
$media = $item->children('http://search.yahoo.com/mrss/');

//get the title of video
$videoTtitle = $media->group->title;

//get the thumbnail of video
//as more than one image exists so we just need the first image so
$thumbAtt = $media->group->thumbnail[0]->attributes();
$thumbUrl = $thumbAtt['url'];

//get the url of video player --> $playerAtt = $media->group->player->attributes();
$videoUrl = $playerAtt['url'];

//get the total views and total favorites for the video , inside yt tag
$yt = $item->children('http://gdata.youtube.com/schemas/2007');

//get the statistics attributes
$statAtt = $yt->statistics->attributes();
//total video views count
$totalViews = $statAtt['viewCount'];
//total favorites count for the video
$totalFavs = $statAtt['favoriteCount'];


//get the total length of video -- yt tag again
$yt = $media->children('http://gdata.youtube.com/schemas/2007');
$lengthAtt = $yt->duration->attributes();
//total video length in seconds
$videoLength = $lengthAtt['seconds'];

//get the name of user who posted the video
$authorName = $item->author->name;
} //end of foreach

?>

After getting all the values for most viewed videos using php you can easily format it and display on your site.

17 May, 2010

maximum value from an array

Finding maximum value from an array using php is quite simple. Following code finds the maximum value from an array.

$maxValue = $resultArr[0];
foreach($searchArr as $val) {
//check for all the values for maximum value and compare it with default value
if($val["total_points"] > $maxPoint) {
$maxPoint = $val["total_points"];
}
}
echo "Maximum value is:".$maxValue;
?>
//Similarly minimum value in an array can also be found just by changing the if condition

16 May, 2010

Create XML without error using PHP arrays

Creating XML dynamically using php is quite simple . DOMDocument can be used for creating such xml file from arrays.
Check out following PHP code folr dynamic creation and output it in browser

$books = array(
array (
id => 1,
author => "Someone",
name => "Professional PHP"
),
array (
id => 2,
author => "Nicholas C",
name => "Professional Ajax"
),
array (
id => 3,
author => "Joe Williams",
name => "Beginning PHP"
)
);

$dom = new DomDocument();
$dom->formatOutput = true;

$root = $dom->createElement( "books" );
$dom->appendChild( $root );

foreach( $books as $book )
{
$bn = $dom->createElement( "book" );
$bn->setAttribute( 'id', $book['id'] );

$author = $dom->createElement( "author" );
$author->appendChild( $dom->createTextNode( $book['author'] ) );
$bn->appendChild( $author );

$name = $dom->createElement( "name" );
$name->appendChild( $dom->createTextNode( $book['name'] ) );
$bn->appendChild( $name );
$root->appendChild( $bn );
}
//output the xml in browser
header( "Content-type: text/xml" );
echo $dom->saveXML();

//or you can save the xml in file by doing the following
$dom->save("/somedirname/somefile.xml");
?>

Xpath in PHP

XPath allows you to retrieve any infromation from xml data. Working with xpath in php is quite simple in some sense
and quite complex in some sense. Some simple xpath queries are explained as a beginning for xpath using php.
Consider following XML file, saved as test.xml




Professinal PHP
Someone not me

One
Two


Beginning PHP
PHP with Ajax
PHP .NET



Now to load the xml file and perform XPath query


$doc = new DOMDocument();
//load the xml file
$doc->load("test.xml");

//create XPath
$newXpath = new DOMXPath($doc);
//get all the title tags from the loaded xml
$books = $newXpath->query("/books/book/title");
//show all the title values such as Professional PHP, Beginning PHP, PHP with Ajax and PHP .NET
foreach($books as $book) {
echo $book->nodeValue."
";
}

//now to get only the title that has certain attributes value such as isbn value in this case
//we do the following, following code shows title Beginning PHP
$onlyBook = $newXpath->query("/books/book[@isbn='1234']/title");

//to get title depending on some values, such as
//following code shows Professional PHP
$firstTitlte = $newXpath->query("/books/book/srcs[src='One' or src='Two']/../title");
?>

14 May, 2010

Login to Gmail with curl

Following code is used to login to gmail using curl. The code is quite simple, for curl options please check php manual.
After loging in to gmail with curl provided below, user can then get their contact list of calendar. Only the logging in step is given
in this code. If the gmail login is successfull, then a unique auth key is obtained and if login fails then nothing is returned.

//store username and password and some values in array
$clientPost = array(
"accountType" => "HOSTED_OR_GOOGLE",
"Email" => "gmailusername",
"Passwd" => "gmailpassword",
"service" => "cp",
"source" => "leaveurdream" // you can name it anything you want
);
//get the gmail login url
$clientUrl = "https://www.google.com/accounts/ClientLogin";
//initialize the curl object
$curl = curl_init($clientUrl);
//set curl option to indicate that we are doing POST
curl_setopt($curl, CURLOPT_POST, true);
//pass the post data array as parameters
curl_setopt($curl, CURLOPT_POSTFIELDS, $clientPost);
//set the following line for SSL and authentication
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
//set option for not checking the peer's certificate
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
//do not echo the data in the browser but save it as string
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
//get the response after executing our curl
$response = curl_exec($curl);

//perform a regular expression match to get the auth key from $response variable
//if the auth key is found then user is logged in successfully else login has failed
preg_match("/Auth=([a-z0-9_\-]+)/i", $response, $matches);
$auth = $matches[1];
//echo the auth key
echo $auth;
?>

12 May, 2010

Yahoo login using curl

Following code can be useful if you are trying to sync your custom php calendar with yahoo calendar using curl. Please check php manual for detailed description about setting curl options. The script for login to yahoo using curl in php is simple and short and can be of help at times for developers like me.

$serviceUrl = "http://calendar.yahoo.com/";
$authUrl = "http://login.yahoo.com/config/login?";
$userAgent = "YahooSeeker-Testing/v3.9 (compatible; Mozilla 4.0; MSIE 5.5; http://search.yahoo.com/)";
$referer = "http://my.yahoo.com";
$login = "yourusername";
$password = "yourpassword";
$numPostData = 22;
$cookieFileJar = "cookie.txt";
$cookie = 0;
$postData = "login=$login&passwd=$password&.src=&.tries=5&.bypass=&.partner=&.md5=&.hash=&.intl=us&.tries=1&.challenge=ydKtXwwZarNeRMeAufKa56.oJqaO&.u=dmvmk8p231bpr&.yplus=&.emailCode=&pkg=&stepid=&.ev=&hasMsgr=0&.v=0&.chkP=N&.last=&.done=" . $serviceUrl;

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);

// Set the referrer
curl_setopt($ch, CURLOPT_REFERER, $referer);

// Set the authentication url
curl_setopt($ch, CURLOPT_URL, $authUrl);

// Set number of post fields
curl_setopt($ch, CURLOPT_POST, $numPostData);

//Set post data in key=value pair such as login=yourusername
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);

//Set filename for storing cookie information
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFileJar);

//Set ffilename for checking the stored cookie information
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);

//Set option for cookie
curl_setopt($ch, CURLOPT_COOKIE, $cookie);

//set this to output the result as string and not output directly ot browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

//set this value to 1 if you want to redirect to the url you provided as service url
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);

//Set this option if you do not want to verify ssl
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

//set this option if you do not want to verify peer's certificate
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

//now execute the curl
$res = curl_exec($ch);

//check if the username and password is valid
if ((preg_match("/invalid/i", $res)) || (preg_match("/not yet taken/i", $res))) {
echo "Invalid Login";
}
else {
//if CURLOPT_FOLLOWLOCATION is set to 1 then after logging in successfully user is directed to url that is specified as service url
echo "Logged In";
}
?>

11 May, 2010

Get total length of Video in PHP


//Total Length of video can be userful at many cases. Following code sample shows
// how to get the total length or duration of any video file

//get the filename of video
$uploadVideoFile = $_FILE["fleVideo"]["name"];

//turn on the output buffering
ob_start();

//execute the the ffmpef command, where -i is the input
//the 2>&1 is done to redirect standard error (stderr) to standard output(stdout)
system("/path/to/ffmpeg -i $uploadVideoFile 2>&1");
//now get the contents
$totalDuration = ob_get_contents();

//clear the output buffer and turn off the output buffering done by ob_start()
ob_end_clean();

//perform a regular expression match
//check for the pattern Duration: ... in $duration and return matches
preg_match('/Duration: (.*?),/', $duration, $matches);

//found the matches
//this is the total length of video
$totalLength = $matches[1];
echo "Total Length of the video is:".$totalLength;
?>

04 May, 2010

Access folder inside nested folders in PHP


//Access nested folders contents using PHP
<?php
function getDir($id=0,$maxLvl=20){
$id1=$id;
$id=str_pad($id,$maxLvl,0,STR_PAD_LEFT);
$dir=NULL;
for($i=0;$i<$maxLvl-2;$i=$i+2){
$dir.=substr($id,$i,2)."/";
$dir1=substr($id,$i,2);
if(!file_exists($dir1))
mkdir($dir1);
chdir($dir1);
}
if(!file_exists($id1))

mkdir($id1);

return $dir.$id1;
}
?>

Create nested folders using PHP


Create maximum levels of nested folders using PHP
<?php
function getWDir($id=0,$maxLvl=20){
$id1=$id;
//add 0 to the left
$id=str_pad($id,$maxLvl,0,STR_PAD_LEFT);
$dir=NULL;
for($i=0;$i<$maxLvl-2;$i=$i+2){
//get the sub-strings for generating multiple folders
$dir.=substr($id,$i,2)."/";
$dir1=substr($id,$i,2);
}
return $dir;
}
?>

XML formatted output of Database Schema using PHP

The following php code tends to be useful to export database schema as xml format.

Get Database Schema(table and fields names) as XML using PHP
<?php
$user = "root";
$passwd = "";
$host = "localhost";
$dbase = "testdb";

//connect to database
$conn = mysql_connect($host, $user, $passwd) or die("Could not connect");
//select the database
mysql_select_db($dbase);

//form the query
$tablesArr = array();
$resultQuery = "SHOW TABLES FROM ".$dbase;
$result = mysql_query($resultQuery);
while($res = mysql_fetch_row($result)) {
$tablesArr[] = $res[0];
}
mysql_free_result($result);
//generate xml formatted output
header("Content-Type: text/xml");
?>
<dbschema>
<?php foreach($tablesArr as $tables) { ?>
<table name="<?php echo $tables; ?>">
<?php
$fields = mysql_query("SHOW FIELDS FROM ".$tables);
while($field_res = mysql_fetch_row($fields)) {
?>
<field name="<?php echo htmlentities($field_res[0]); ?>" type="<?php echo htmlentities($field_res[1]); ?>" />
<?php
} //end of while
mysql_free_result($fields);
?>
</table>
<?php
} //end of foreach
?>
</dbschema>

Find distance between two cities using lattitude and longitude using Google Maps


Distance can be calculated using lattitude and longitude obtained from google maps api, using the following code:
//Get the lattitude and longitude of two cities first -- returns json format data
$address1 = urlencode($addressLine1).",+".urlencode($city1).",+".urlencode($statePrefix1);
$address2 = urlencode($addressLine2).",+".urlencode($city2).",+".urlencode($statePrefix2);

$geoCode1 = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".$address1."&sensor=false");
$geoCode2 = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=".$address2."&sensor=false");

//now get lat and long
$output1 = json_decode($geoCode1);
$lat1 = $output1->results[0]->geometry->location->lat;
$lng1 = $output1->results[0]->geometry->location->lng;

$output2 = json_decode($geoCode2);
$lat2 = $output2->results[0]->geometry->location->lat;
$lng2 = $output2->results[0]->geometry->location->lng;

//now get the distance
calculate_distance($lat1, $lng1, $lat2, $lng2, "K");

//function calculate_distance
function calculate_distance($lat1, $long1, $lat2, $long2, $unit) {
$theta = $lon1 - $lon2;
$dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) + cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
$dist = acos($dist);
$dist = rad2deg($dist);
$miles = $dist * 60 * 1.1515;
$unit = strtoupper($unit);
if ($unit == "K") {
return ($miles * 1.609344);
}
else if ($unit == "N") {
return ($miles * 0.8684);
}
else {
return $miles;
}
}

Sort Multi-dimensional Array By Value

A multi-dimensional array can be sorted using following code snippet.
function subval_sort($arr, $subKey, $sort) {
foreach($arr as $k => $v) {
$b[$k] = strtolower($v[$subKey]);
}
$sort($b);
foreach($b as $key => $val) {
$c[] = $arr[$key];
}
return $c;
}
$testArr = array(
0 => array("name" => "test", age => 20),
1 => array("name" => "smith", age=>30)
);
Usage: subval_sort($testArr, "name", arsort);

PHP Video Conversion & Thumbnail -- FFMPEG

To convert video to flv format add the following code:
$source = "path/somesource.mpg";
$destination = "path/somefilename.flv";
exec("/path/to/ffmpeg -i $source -ab 128 -ar 22050 -b 300000 -r 25 -s 320×240 $destination");

And to generate video first-frame thumbnail, add the following code:
exec("/path/to/ffmpeg -i $source -ss 1.4 -vframes 1 -f image2 $screenshotImg");