Most Useful PHP Snippets

Here we have some set of Useful PHP Snippets, which are useful for PHP Developers. That you can easily add in your projects and help you save your time.

Most Useful PHP Snippets

1) Check if a date today’s date

$date = "2017-01-20 20:38:47";

if(date('Ymd') == date('Ymd', strtotime($date))){
   echo "today date";
}

2) Get image extension

<?php
$file_path = "https://www.thecodedeveloper.com/demo/Code-Developer-Logo.png";
$fileinfo = pathinfo($file_path);
print_r($fileinfo);

/*
Output
Array
(
    [dirname] => https://www.thecodedeveloper.com/demo
    [basename] => Code-Developer-Logo.png
    [extension] => png
    [filename] => Code-Developer-Logo
)
*/

echo $fileinfo['extension']; //get image extension

?>

3) Add http:// to URL if missing

function addhttpPrefixToUrl($url) {
	if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
		$url = "http://" . $url;
	}
	return $url;
}

echo addhttpPrefixToUrl('thecodedeveloper.com');

/*
Output: https://thecodedeveloper.com
*/

?>

4) Get the Current Page URL

<?php
function curPageURL()
{
	if (isset($_SERVER["HTTPS"]) && !empty($_SERVER["HTTPS"]) && ($_SERVER["HTTPS"] != 'on')) {
		$url = 'https://' . $_SERVER["SERVER_NAME"];
	} else {
		$url = 'http://' . $_SERVER["SERVER_NAME"];
	}
	if (($_SERVER["SERVER_PORT"] != 80)) {
		$url .= $_SERVER["SERVER_PORT"];
	}
	$url .= $_SERVER["REQUEST_URI"];
	return $url;
}

echo curPageURL();

?>

5) Find email address in string

<?php
function findEmailAddress($string){
	$regex = '/\S+@\S+\.\S+/';
	preg_match_all($regex, $string, $emails,  PREG_PATTERN_ORDER);
	return $emails;
}

$string = "The Code Developer is a Programming Blog vikastyagi87@gmail.com";

$filter = findEmailAddress($string);

print_r($filter);

/*
Output
Array
(
    [0] => Array
        (
            [0] => vikastyagi87@gmail.com
        )

)
*/

?>

6) Generate Random Alphanumeric String

This is a simple function that allows you to generate random strings containing Letters and Numbers (alphanumeric) using PHP.

function random_code($limit)
{
	return substr(base_convert(sha1(uniqid(mt_rand())), 16, 36), 0, $limit);
}

echo random_code(8);

/*
Here's the output samples

mocpkwbn
460djcsn
j1m10z0t
4kj9cy68
*/

7) Check if a string contains a particular word

Using strpos function

$string = "The Code Developer is a Programming Blog Maintained by Vikas Tyagi";

if (strpos($string, 'Code') !== false) {
    echo 'Found';
} else {
    echo 'Not Found';
}


8) Calculate days between two dates

$start_date = strtotime('2016-01-01');
$end_date = strtotime('2016-01-21');
echo $days_difference = ceil(abs($end_date - $start_date) / (60 * 60 * 24));

/*
Output : 20
*/

9) Check if a date is today, past or tomorrow

$yourdate = "2016-01-26";
if(strtotime($yourdate) < strtotime(date('Y-m-d')))
{
   echo "past date";
}
else if (strtotime($yourdate) == strtotime(date('Y-m-d'))){
  echo "today date";
}
else if (strtotime($yourdate) > strtotime(date('Y-m-d'))){
  echo "tomorrow date";
}

10) Get User IP Address


if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    echo $ip=$_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    echo $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    echo $ip=$_SERVER['REMOTE_ADDR'];
}

/*
Output look like: 125.62.126.49
*/


11) Add target=”_blank” to all links

$string = "<a href='https://www.thecodedeveloper.com/'>The Code Developer</a> is a Programming Blog.";
$string = preg_replace("/<a(.*?)>/", "<a$1 target='_blank'>", $string);
echo $string;

/*
HTML Output : <a href="https://www.thecodedeveloper.com/" target="_blank">The Code Developer</a> is a Programming Blog.
*/

12) Calculate age

<?php
$birthDayDate = "07/02/1987"; //here date in mm/dd/yyyy format
//explode the date to get month, day and year
$birthDayDate = explode("/", $birthDayDate);
//get age from date or birthdate
$age       = (date("md", date("U", mktime(0, 0, 0, $birthDayDate[0], $birthDayDate[1], $birthDayDate[2]))) > date("md") ? ((date("Y") - $birthDayDate[2]) - 1) : (date("Y") - $birthDayDate[2]));
echo "Age is:" . $age;
?>

/*
Output:
Age is:30
*/

Leave A Reply

Your email address will not be published.