Friday 17 June 2016

How to get the file extension using PHP

Question:

How can I grab the extension of a file I have uploaded using PHP?

Answer:

PHP comes with a built-in function called ‘pathinfo()’ which allows you to get the extension of file you have uploaded.
$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
echo $ext;

Difference between double and triple equal to operators in PHP

This is one of the most common interview questions in PHP. Both == and === are comparison operators which are used to compare two values. But their is a major difference between the two. The ‘==’ (double equal to) compares and test if the two values on left and right side are equal. On the other hand, ‘===’ (triple equal to) tests if the two values are equal as well as check if they are of same data type. Let me explain you with help of an example,
<?php
$x = 100; $y = "100";
if($x == $y){
 echo "Yes";
}else{
 echo "No";
}
?>
The output of above code will be “YES” as  “==” operator compares only values and values in $x and $y are same.
<?php
$x = 100; $y = "100";
if($x === $y){
 echo "Yes";
}else{
 echo "No";
}
?>
The output of above code will be “NO” as even the values in $x and $y are same, there data type is different.

How to Get the Current Page URL in PHP?

When developing PHP based web application,  sometimes you need to grab the URL of current page.  Using the following PHP code snippet you will be able to get the URL of current webpage.
<?php
/**
 * Grabs and returns the URL of current page.
 * @param   none
 * @return  URL of current page
 */
function grabCurrentURL(){
 if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
  $url = "https://";
 }else{
  $url = "http://";
 }
 $url .= $_SERVER['SERVER_NAME'];
 if($_SERVER['SERVER_PORT'] != 80){
  $url .= ":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
 }else{
  $url .= $_SERVER["REQUEST_URI"]; 
 }
 return $url;
}

echo grabCurrentURL();
?>

Simple PHP Password Generator

When building web based applications, often you need to generate passwords for users. This is a simple PHP script which allows you to generate random passwords.
<?php
/**
 * Generates random passwords.
 * @param   int  Password Length (Default : 10)
 * @return  Random String
 * @author  Harshal Limaye (http://coffeecupweb.com/)
 */
function genPass($len = 10) {
    $charPool = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
    $pass = array();
    $length = strlen($charPool) - 1;
    for ($i = 0; $i < $len; $i++) {
        $n = rand(0, $length);
        $pass[] = $charPool[$n];
    }
    return implode($pass);
}
echo genPass();
?>

How to extract Zip Files with PHP?

In this post, I will show you, how to extract zip/compressed files using PHP. PHP has built-in extensions for dealing with compressed files.
Following PHP function can be used to unzip the compressed files. It accepts two parameters, source i.e full path to zip file and destination i.e path to which files will be extracted.
<?php
//extract a file with php
function extractZip($src,$dest){
 $zip = new ZipArchive;
 $res = $zip->open($src);
 if ($res === TRUE) {
  $zip->extractTo($dest);
  $zip->close();
  echo 'Files Extracted Successfully!';
 } else {
  echo 'Extraction Failed!';
 }
}

$src = "zip/file.zip";
$dest = "extractedfile/1/";
echo extractZip($src,$dest);
?>

How to create a zip file in php?

In one of my previous post, We  have already seen How we can extract Zip Files using PHP. In this tutorial, we are going to create a Zip file with PHP. To perform this task, we are going to use a built-in extension in PHP known as ZipArchive classs.
This is a very basic PHP function which accepts two parameters array of files to be zipped and name of zip file to be created.
//Creating a Zip File Using PHP
function genZip($files = array(),$zipName){
 $zip = new ZipArchive();
 $zip->open($zipName.'.zip', ZipArchive::CREATE);
 foreach($files as $file){
  $zip->addFile($file);
 }
 $zip->close();
}
Usage:
//Usage of genZip function
$files = array(
  'file1.pdf',
  'file2.pdf',
  'file3.pdf',
  'folder2/file4.pdf',
  'folder2/file5.pdf'
 );
$zipName = 'myfiles';
genZip($files,$zipName);

How to get youtube video ID from url using php?

Here’s a handy PHP code snippet which allows you to extract the video ID of a YouTube video from URL. All you need to do is pass the YouTube URL to the getYouTubeId() function.
//get video id from youtube url
function getYouTubeId($url){
 parse_str( parse_url( $url, PHP_URL_QUERY ), $my_array_of_vars );
 return $my_array_of_vars['v'];
}
echo getYouTubeId('https://www.youtube.com/watch?v=y2Ky3Wo37AY');
The Above code will output,
y2Ky3Wo37AY

Export Data From MySQL table to CSV File using PHP

CSV  stands for  Comma separated values. It is one of the most widely used format to transfer data from one application to another in a tabular form. In this post, we are going to learn to export the data from database to a CSV file.
The Script:
<?php 
//Connect and select a database
mysql_connect('localhost','root','');
mysql_select_db('webapp');

//Output headers to make file downloadable
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=spreadsheet.csv');

//Write the output to  buffer
$data = fopen('php://output', 'w');

//Output Column Headings
fputcsv($data,array('Name','Email Address'));

//Retrieve the data from database
$rows = mysql_query('SELECT name, email FROM users');

//Loop through the data to store them inside CSV
while($row = mysql_fetch_assoc($rows)){
 fputcsv($data, $row);
}
As you can see, on line 3 and 4, we are connecting our script with the database. Then, on line 7 we are producing HTTP headers to specify the MIME type of the file which is text/csv. On the next line, we have set the Content-Disposition toattachment to make the file downloadable and spreadsheet.csv is the name of the file which will be downloaded.
Line 11 creates a write-only output stream which allows us to write the data to the buffer. On line 14, we are printing column headings which in out case areName and Email Address,  you can change them as per your requirement. And on line 17, we are retrieving the data from database using a simple MySQL query.
And online 20 and 21, we are looping through retrievedthe data and writing it to our output stream.

How to Create SEO friendly URLs in PHP

This is a handy PHP code snippet which accepts a regular string as input and returns a SEO friendly slug which can become a part of a URL.
public function stringToSlug($string){
  //Remove white spaces from both sides of a string
  $string = trim(string);
  
  //Lower case everything
  $string = strtolower($string);
  
 //Make alphanumeric (removes all other characters)
 $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
  
 //Clean up multiple dashes or whitespaces
 $string = preg_replace("/[\s-]+/", " ", $string);
  
 //Convert whitespaces and underscore to dash
 $string = preg_replace("/[\s_]/", "-", $string);
  
 return $string;
}

How To Remove Last Comma From String Using PHP?

Generally, developers use loops to create a comma separated lists in stringformat. But, after the loop you end with a trailing comma at the end of the string.

To remove this comma we are going to use PHP’s built rtrim function. rtrim function is used to strip off whitespaces and predefined characters from right side of the string. It accepts two parameters,
  1. String – String we want to trim (Required)
  2. Character – Characters which we want to strip (Optional)
Here’s an example code:
$string = "a, b, c, d,";
$filtered = rtrim($string, ',');
echo $filtered;
As you can, we are passing a variable with a comma separated list and a comma(,) as second parameter. The output of above code is as follows.
a, b, c, d

How to Get Yesterday’s Date Using PHP?

You can use the following code to get yesterday’s date in PHP. To do this, we are using PHP’s built-in date() function.
<?php echo date("Y-m-d", time() - (60*60*24) ); ?>

<?php echo date("Y-m-d", strtotime("-1 day"));  ?>

<?php echo date("Y-m-d", strtotime("yesterday")); ?>

<?php echo date("Y-m-d", mktime(0, 0, 0, date("m"),date("d")-1,date("Y"))); ?>

How to convert a negative number to a positive number using PHP

PHP comes with a built-in function called abs() [Absolute Value] to convert a negative number to positive number. It accepts one parameter the number itself. The number can be a integer or a float. If the parameter supplied to the function is float it will return float value. Otherwise, it will return an integer.
Examples:
<?php
echo abs(-6.2);  // 6.2 (float)
echo abs(19);    // 19 (integer)
echo abs(-2);    // 2 (integer)
?>

Time Ago Function in PHP

Here’s a lightweight PHP function which accepts a date as a parameter and converts it into “sometime age” output.ime_ao($date) {
    if (empty($date)) {
        return "Please enter a date!";
    }
    $duration_in = [
        "second", 
        "minute", 
        "hour", 
        "day", 
        "week", 
        "month", 
        "year", 
        "decade"
    ];
    $len = [
        "60", 
        "60", 
        "24", 
        "7", 
        "4.35", 
        "12", 
        "10"
    ];
    $now = time();
    $unixDate = strtotime($date);

    if (empty($unixDate)) {
        return "Please enter a valid date!";
    }

    if ($now > $unixDate) {
        $diff = $now - $unixDate;
        $tense = "ago";
    } else {
        $diff = $unixDate - $now;
        $tense = "from now";
    }
    for ($j = 0; $diff >= $len[$j] && $j < count($len) - 1; $j++) {
        $difference /= $len[$j];
    }
    $diff = round($diff);
    if ($diff != 1) {
        $duration_in[$j].= "s";
    }
    return "$diff $duration_in[$j] {$tense}";
}
Usage:
echo time_ago($date);

How to Remove Empty Array Elements in PHP

Here’s a handy code snippet which allows you to remove empty elements from an array in PHP.
<?php
function ccw_remove_empty_element_from_array($data)
{
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            $data[$key] = ccw_remove_empty_element_from_array($data[$key]);
        }

        if (empty($data[$key])) {
            unset($data[$key]);
        }
    }

    return $data;
}

PHP - Get age from date of birth


PHP >= 5.3.0

<?php
# object oriented
 $from = new DateTime('1970-02-01');
 $to = new DateTime('today');
echo $from->diff($to)->y;
# procedural
echo date_diff(date_create('1970-02-01'), date_create('today'))->y;
?>
****************************************************


<?php
 /**
* Simple PHP age Calculator
 * * Calculate and returns age based on the date provided by the user.
 * @param date of birth('Format:yyyy-mm-dd').
 * @return age based on date of birth */
 function ageCalculator($dob){
         if(!empty($dob)){
                    $birthdate = new DateTime($dob);
                   $today = new DateTime('today');
                   $age = $birthdate->diff($today)->y;
                   return $age;
         }else{
             return 0;
          }
}
 $dob = '1992-03-18';
echo ageCalculator($dob);
?>
**************************************
<?php
$dob='1981-10-07';
$diff = (date('Y') - date('Y',strtotime($dob)));
echo $diff;
?>
**********************************************************
<?php
function age($birthday){
 list($day, $month, $year) = explode("/", $birthday); 
 $year_diff = date("Y") - $year; 
 $month_diff = date("m") - $month;
 $day_diff = date("d") - $day;
 if ($day_diff < 0 && $month_diff==0)
 $year_diff--; 
if ($day_diff < 0 && $month_diff < 0)
 $year_diff--;
 return $year_diff;
 }
#or the same function that accepts day, month, year as parameters :
function age($day, $month, $year){ 
$year_diff = date("Y") - $year; 
$month_diff = date("m") - $month;
 $day_diff = date("d") - $day; 
 if ($day_diff < 0 && $month_diff==0) 
$year_diff--;
 if ($day_diff < 0 && $month_diff < 0) 
$year_diff--; 
return $year_diff; 
}
#You can use it like this :echo age("20/01/2000");


#which will output the correct age (On 4 June, it's 14).

?> 
**************************************************************
Calculate Age With PHP
Checking dates in PHP can be problematic as PHP primarily concerns itself with date manipulation which revolves around unix timestamps. This is a good thing, mostly. Unix timestamps however, have not concept of leap years, thus it is difficult, though not impossible, to get an accurate date calculation from them. When dates need to be accurate for legal reasons, it is vital that the leap years are considered.

With strtotime()
This first method makes use of the PHP strtotime() function and increments a 1 year on each iteration.


<?php

/*** make sure this is set ***/
date_default_timezone_set('Europe/London');

/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge( $dob, $tdate )
{
        $age = 0;
        while( $tdate > $dob = strtotime('+1 year', $dob))
        {
                ++$age;
        }
        return $age;
}
?>
EXAMPLE USAGE


<?php

/*** a date before 1970 ***/
$dob = strtotime("april 20 1961");

/*** another date ***/
$tdate = strtotime("june 2 2009");

/*** show the date ***/
echo getAge( $dob, $tdate );

?>

Output
48
Using the DateTime Class
The PHP DateTime class allow a little neater code by providing an Object Oriented interface to date functions. By passing a DateInterval object to the DateTime class the DateTime object can be increment 1 year on each iteration until it reaches the target date. The DateTime::add() method requires PHP >= 5.3.


<?php

/*** set the default timezone ***/
date_default_timezone_set('Europe/London');

/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge( $dob, $tdate )
{
        $dob = new DateTime( $dob );
        $age = 0;
        $now = new DateTime( $tdate );
        while( $dob->add( new DateInterval('P1Y') ) < $now )
        {
                $age++;
        }
        return $age;
}

?>
EXAMPLE USAGE
<?php

/*** a date before 1970 ***/
$dob = "April 20 1961";

/*** another date ***/
$tdate = "21-04-2009";

/*** show the date ***/
echo getAge( $dob, $tdate );

?>
Output
48
More DateTime Goodness
Following on with PHP 5.3 and above, the DateTime::diff() method is provided for just this sort of calculation. By using this method, the code is cut down considerably and the calculations done internally.


<?php

/*** dont forget to set this ***/
date_default_timezone_set('Europe/London');

/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge( $dob, $tdate )
{
        $d1 = new DateTime( $dob );
        $d2 = new DateTime($tdate );
        $age = $d2->diff( $d1 );
        return $age->y;
}

?>
EXAMPLE USAGE


<?php

/*** a date before 1970 ***/
$dob = "April 20 1961";

/*** another date ***/
$tdate = "21-04-2009";

/*** show the date ***/
echo getAge( $dob, $tdate );

?>
48
**********************************************************************
<?php 
// PHP 5.3-
function birthday($birthday){ 
    $age = strtotime($birthday);
    
    if($age === false){ 
        return false; 
    } 
    
    list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age)); 
    
    $now = strtotime("now"); 
    
    list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now)); 
    
    $age = $y2 - $y1; 
    
    if((int)($m2.$d2) < (int)($m1.$d1)) 
        $age -= 1; 
        
    return $age; 
} 

echo birthday('1981-05-18'); 

// PHP 5.3+
function birthday($birthday) {
    $age = date_create($birthday)->diff(date_create('today'))->y;
    
    return $age;
}

echo birthday('1981-05-18'); 
?> 

************************************************************
MySQL >= 5.0.0
SELECT TIMESTAMPDIFF(YEAR, '1970-02-01', CURDATE()) AS age