1. MySQL Database connection using PHP

<?php
$host="localhost"; $uname="database username"; $pass="database password"; $database = "database name"; $connection=mysql_connect($host,$uname,$pass) or die("Database Connection Failed"); $result=mysql_select_db($database) or die("database cannot be selected"); ?>

2. PHP function to display limited words from a string

function words_limit( $str, $num, $append_str='' ){
$words = preg_split( '/[\s]+/', $str, -1, PREG_SPLIT_OFFSET_CAPTURE );
 if( isset($words[$num][1]) ){
   $str = substr( $str, 0, $words[$num][1] ).$append_str;
 }
unset( $words, $num );
return trim( $str );>
}

echo words_limit($yourString, 50,'...'); 

or

echo words_limit($yourString, 50); 

3. Display thumbnail image from youtube or vimeo video

function video_image($url){
   $image_url = parse_url($url);
     if($image_url['host'] == 'www.youtube.com' || 
        $image_url['host'] == 'youtube.com'){
         $array = explode("&", $image_url['query']);
         return "http://img.youtube.com/vi/".substr($array[0], 2)."/0.jpg";
     }else if($image_url['host'] == 'www.youtu.be' || 
              $image_url['host'] == 'youtu.be'){
         $array = explode("/", $image_url['path']);
         return "http://img.youtube.com/vi/".$array[1]."/0.jpg";
     }else if($image_url['host'] == 'www.vimeo.com' || 
         $image_url['host'] == 'vimeo.com'){
         $hash = unserialize(file_get_contents("http://vimeo.com/api/v2/video/".
         substr($image_url['path'], 1).".php"));
         return $hash[0]["thumbnail_medium"];
     }
}

<img src="<?php echo video_image('youtube URL'); ?>" />

4. PHP function to get age from date of birth

function age_from_dob($dob){
$dob = strtotime($dob);
$y = date('Y', $dob);
 if (($m = (date('m') - date('m', $dob))) < 0) {
  $y++;
 } elseif ($m == 0 && date('d') - date('d', $dob) < 0) {
  $y++;
 }
return date('Y') - $y;
}

echo age_from_dob('2005/04/19'); date in yyyy/mm/dd format.

5. Using Cookies in PHP

Save value is cookies
setcookie("name", 'value', time()+3600*60*30);

Display cookie value
if ($_COOKIE["name"]!=""){
$_SESSION['name'] = $_COOKIE["name"];
}

6. Random password generation using PHP

Option-1
echo substr(md5(uniqid()), 0, 8); 

Option-2
function rand_password($length){
  $chars =  'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  $chars .= '0123456789' ;
  $chars .= '!@#%^&*()_,./<>?;:[]{}\|=+';

  $str = '';
  $max = strlen($chars) - 1;

  for ($i=0; $i < $length; $i++)
    $str .= $chars[rand(0, $max)];

  return $str;
}

echo rand_password(16);

7. Get date difference PHP

date_default_timezone_set("Asia/Calcutta");

function dt_differ($start, $end){
  $start = date("G:i:s:m:d:Y", strtotime($start));
  $date1=explode(":", $start);

  $end  = date("G:i:s:m:d:Y", strtotime($end));
  $date2=explode(":", $end);
	
  $starttime = mktime(date($date1[0]),date($date1[1]),date($date1[2]),
  date($date1[3]),date($date1[4]),date($date1[5]));
  $endtime   = mktime(date($date2[0]),date($date2[1]),date($date2[2]),
  date($date2[3]),date($date2[4]),date($date2[5]));

  $seconds_dif = $starttime-$endtime;

  return $seconds_dif;
}

Call In Action

	
<?php
  $today = date("Y-n-j H:i:s");
  $fromday = "2012-12-31 23:59:59";
  $timediffer = dt_differ($fromday, $today);
  echo $timediffer." seconds";
?>

8. Convert seconds to days hour and minutes in php

function seconds2days($mysec) {
    $mysec = (int)$mysec;
    if ( $mysec === 0 ) {
        return '0 second';
    }

    $mins  = 0;
    $hours = 0;
    $days  = 0;


    if ( $mysec >= 60 ) {
        $mins = (int)($mysec / 60);
        $mysec = $mysec % 60;
    }
    if ( $mins >= 60 ) {
        $hours = (int)($mins / 60);
        $mins = $mins % 60;
    }
    if ( $hours >= 24 ) {
        $days = (int)($hours / 24);
        $hours = $hours % 60;
    }

    $output = '';

    if ($days){
        $output .= $days." days ";
    }
    if ($hours) {
        $output .= $hours." hours ";
    }
    if ( $mins ) {
        $output .= $mins." minutes ";
    }
    if ( $mysec ) {
        $output .= $mysec." seconds ";
    }
    $output = rtrim($output);
    return $output;
}

Call in action:

$timediffer we get it from our previous function.
<?php echo seconds2days($timediffer); ?>

9. Convert any date format to Mysql Date format using PHP

<?php
function convertToMysqlDate($mydate, $dtformat) {
    $dt = new DateTime();
    $date = $dt->createFromFormat($dtformat, $mydate);
    $convertdt = $date->format('Y-m-d');
    return $convertdt;
}

$dtformat = 'Y/d/m';
$dte='2012/25/12';
// Or you can also convert any date to above date format
//$dte = date(strtotime('25/12/2013'),$dtformat);

$newdt = convertToMysqlDate($dte, $dtformat);

echo "Converted Date:" . $newdt;
?>

10. Unzip Files in Web server

<?php
$zip = zip_open("moooredale.zip");
  if ($zip) {
   while ($zip_entry = zip_read($zip)) {
   $fp = fopen(zip_entry_name($zip_entry), "w");
   if (zip_entry_open($zip, $zip_entry, "r")) {
   $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));
   fwrite($fp,"$buf");
   zip_entry_close($zip_entry);
   fclose($fp);
 }
}
zip_close($zip);
}
?>
Click here to know how to Zip multiple files.

11. Convert  Rupees to Dollar In Real Time in PHP

<?php
function rupees_to_dollar($Amount, $currencyfrom, $currencyto) {
$buffer = file_get_contents('http://finance.yahoo.com/currency-converter');
preg_match_all('/name=(\"|\')conversion-date(\"|\') 
value=(\"|\')(.*)(\"|\')>/i',$buffer, $match);
$date = preg_replace('/name=(\"|\')conversion-date(\"|\') 
value=(\"|\')(.*)(\"|\')>/i','$4', $match[0][0]);
unset($buffer);
unset($match);
$buffer = file_get_contents('http://finance.yahoo.com/currency/
converter-results/'.$date.'/'.$Amount.'-'.strtolower($currencyfrom).'-to-'.
strtolower($currencyto).'html');
preg_match_all('/<span class=\"converted-result\">(.*)<
\/span>/i', $buffer, $match);
$match[0] = preg_replace('/<span class=\"converted-result\">
(.*)<\/span>/i', '$1',$match[0]);
unset($buffer);
return $match[0][0];
}
?>

Call in action:
<?php
     echo ruppes_to_dollar(32000, "INR", "USD");
?>
Top