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.

Read Also: How to enable mod_rewrite in Ubuntu

function time_ago($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);

Source: http://stackoverflow.com/a/18891474

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.

Changing AngularJS templating brackets

Examples:

<?php
echo abs(-6.2);  // 6.2 (float)
echo abs(19);    // 19 (integer)
echo abs(-2);    // 2 (integer)
?>

 

How To Remove Last Comma From String Using PHP?

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

Useful Read : Export the MySQL database table as CSV format using PHP

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 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.

Useful Read : Export Data From MySQL table to CSV File using PHP

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;
}

 

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.

Quick Tip : PHP script to extract zip files

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 to attachment 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 are Name 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.

I hope you enjoyed the tutorial and fount it useful. In case you have any query, feel free to comment.

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.

Quick Tip : Unzip a file with php

//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

 

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 extract Zip Files with PHP?

In the previous post, we have created a random alphanumeric password generator script. 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.

Quick Tip : Simple PHP Password Generator

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);
?>

Author: rdlowrey

Source: Stack Overflow

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.

Useful Read: Get Current Page URL

<?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();
?>