<?php
function get_age($birth_date){
return floor((time() - strtotime($birth_date))/31556926);
}
echo " I am ".get_age("2000-05-10") ." years old";
?&g...
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;...
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...
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 .=...
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++) {
...
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...
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);
...
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...
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...
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...
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,
String – String we want to trim (Required)
Character – Characters which we want to strip (Optional)
Here’s an example code:
$string = "a, b, c,...
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"))); ?>...
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)
?>...
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);
...
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 >= 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){
...