Code Snippets in PHP

In this article I will explain some important Code Snippets in PHP.

Introduction

In this article I will explain some important Code Snippets in PHP. These snippets are very useful in projects. I explain them step-by-step in this article.

Example1

This example calculates age using date of birth. It is very useful when building communities or social media sites. This function is very fast and simple.

<?php
function age_from_dob($dob)
{
    list($d,$m,$y) = explode('-
', $dob);

    if (($m = (date('
m') - $m)) < 0)
{
       $y++;
  } elseif ($m == 0 && date('
d') - $d < 0)
{
        $y++;
    }
    return date('
Y') - $y;
}
?>

Example2

In this example you must use the Twitter API and you can determine the friendship between two users. Both users however should be online for calculating friendship.

<?php

function make_request($url)

{

       $ch = curl_init();

       curl_setopt($ch,CURLOPT_URL,$url);

       curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);

       $result = curl_exec($ch);

       curl_close($ch);

       return $result;

}

 function get_match($regex,$content) {

       preg_match($regex,$content,$matches);

       return $matches[1];

}

$person1 = 'phpsnippets';

$person2 = 'catswhocode';

//send request to twitter

$url = 'https://api.twitter.com/1/friendships/exist';

$format = 'xml';

$persons12 = make_request($url.'.'.$format.'?user_a='.$person1.'&user_b='.$person2);

$result = get_match('/<friends>(.*)<\/friends>/isU',$persons12);

echo $result; // returns "true" or "false"

?>

Example3

This example calculates the execution time. This example is for debugging purposes. It is useful to be able to calculate the execution time.

<?php

//calculate execution time

$time_start = microtime(true);

$time_end = microtime(true);

$time = $time_end - $time_start;

echo 'Script took '.$time.' seconds to execute';

?>

 

Output


browser.jpg

Example4

This example can be used for browser detection in PHP.

<?php

    $user = $_SERVER ['HTTP_USER_AGENT'];

    echo "<b>Your User Agent is</b>: " . $user;

?>

 

Output


time.jpg

Example5

This example can be used to Base64 Encode and Decode a string or a base64 URL in PHP.

<?php

function base64url_encode($plainText) {

    $base64 = base64_encode($plainText);

    $base64url = strtr($base64, '+/=', '-_,');

    return $base64url;

}

function base64url_decode($plainText) {

    $base64url = strtr($plainText, '-_,', '+/=');

    $base64 = base64_decode($base64url);

    return $base64;

}

?>