Friday 12 May 2017

10 Awesome PHP snippets

10 Awesome PHP snippets

Welcome back, developer's. this article will make a long running on your coding life, underneath are beat 10 valuable pieces i made sense of and most likely thought would be helpful to you. 

These php tips, you may require them on your improvement procedure, and beyond any doubt you require a work round examples. 

These code are helpful and you gone over them more often than not, the easily overlooked detail that matter most, means the most.

1 } How to sanitize user input


You are told the greater part of your coding profession not to trust client's info, it may be spam or infusion, not 100% immaculate, clean and channel clients information is the best alternative, yet that is not 100% secured either but rather felt smidgen safe and secured, beneath is a capacity to clean client's contribution before putting away to your database.

<?php
function cleanInput($text)
{
 //strip tags
 $text = strip_tags($text);
 $text = trim($text);
 return $text;
}
?>

The most effective method to utilize work

<?php
// chow to use function
$name=cleanInput($_POST['name']);
?>

2}  Step by step instructions to approve Email address with PHP

It's essential to approve client email before putting away and planing to utilize them for any reason, i at some point get a kick out of the chance to confirm email deliver just to make certain is not spam and legitimate email. 

With PHP "FILTER_VALIDATE_EMAIL" rest guaranteed a touch of no spam, so you might need to utilize this capacity to legitimate email address is extremely helpful.

<?php
function Is_email($email)
{
 //If the input string is an e-mail, return true
 if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
  return true;
 } else {
  return false;
 }
}
// chow to use function
$email=Is_email($_POST['email']);
?>

3} PHP how old am I? reveal to me my age

This capacity is exceptionally great pleasant, seen on different stage making inquiry identified with this, for the individuals who are taking a shot at online networking stage, this would be extremely useful, telling your client how old they are. 

Note: you can even utilize this capacity to send glad birthday message, at whatever time it coordinates that 'Day and Month' simply let them despite everything you recall that them as your exceptional clients. it proves to be useful too. 

Note: you might need to change "DateTimeZone" is exceptionally welcome or better still use without timeZone.
Please read more on  Date and Time Related Extensions

<?php
//with timeZone.
function howOldAmI($age)
{
  $tz  = new DateTimeZone('Europe/Brussels');

$age = DateTime::createFromFormat('d/m/Y', $a, $tz)->diff(new DateTime('now', $tz))->y;
     return $age;
}
    
     echo howOldAmI('21/04/1993');

    // without timeZone.

function Tellage($b)
{
     $_age = floor((time() - strtotime($b)) / 31556926);
     return $_age;
}
  // echo Tellage('1993/04/21');
?>

4} PHP GET List Of FILES NAMES FROM A Directory

Step by step instructions to Get All Files Names From A Folder. 
This bit beneath will list/demonstrate all your record names in separate of their document augmentations 
In the event that you at any point needed to flaunt your documents name on your envelope, then this script is ideal for you.

<?php
$dir_path = "folder/"; //directory
$options = "";
if(is_dir($dir_path))
{
    $files = opendir($dir_path);
    {
        if($files)
        {
          while(($file_name = readdir($files)) !== FALSE)
          {
              if($file_name != '.' && $file_name != '..')
              {
               // select option with files names
               $options = $options."<option>$file_name</option>";   
               
               // display the file names
               echo $file_name."<br>";
              }
          }
        }
}
}

?>


<!DOCTYPE html>
<html>
    <head>
        
    <title>PHP GET List Of FILES NAMES FROM A Directory </title>
    </head>
    
    <body>
        
        <select>
            <?php echo $options;?>
        </select>
        
    </body>
</html>

5} How to create SEO friendly URL with PHP

Have a perfect cordial url is the request of the day, each body need to keep up SEO standard, if require url like this http://www.codexpresslabs.info/how-to-outline login-page-for-web then you don't need to look any further on this issue, i got you secured. with clean URL work you can have a pleasant looking, amicable and engaging Url for your site or blog.

<?php
function cleanURL($string) {
   $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.
   $string = preg_replace('/[^A-Za-z0-9\-]/', '-', $string); // Removes special chars.

   return preg_replace('/-+/', '-', $string); // Replaces multiple hyphens with single one.
}
//How to use this function
$url=cleanURL($url);
?>

6} Function to converting time to ago format

This is aPHP work with class HowLong, having somethis like this 3 weeks ago, 1 min ago or an hour ago, this capacity would be awesome for web informal community application, of discussion base framework, demonstrating clients to what extent they have been on the web and when last they login and so forth utilizing PHP timestamp.

<?php
function HowLong($timestamp){
 
     $difference = time() - $timestamp;
     $periods = array("sec", "min", "hr", "day", "week", "month", "year", "decade");
     $lengths = array("60","60","24","7","4.35","12","10");
     for($j = 0; $difference >= $lengths[$j]; $j++)
      $difference /= $lengths[$j];
      $difference = round($difference);
     if($difference != 1) $periods[$j].= "s";
      $text = "$difference $periods[$j] ago";
      return $text;
    }
 
// How to use this function
$time=(1482698697); //$timestamp time()

echo HowLong($time);
?>


Note: this can display a long time ago, even decades.

7} How to create secured PHP login function


Approving clients qualifications is a decent method for limiting approve access to some discharge some portion of your site, potentially which is mean for enlisted clients. this capacity will approve, purify each client email and secret key before conceding access to clients, you might need to attempt this on your next venture.

<?php
//database configuration
session_start();
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_DATABASE', 'sociallabs');
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);

//loginfunction start
function loginVal($db, $email, $password)
{
$error="";
if (isset($_POST['email']) && ($_POST['password'])) {

$email = trim($_POST['email']); //Storing email in $email variable.
$password = ($_POST['password']); //Storing password in $password variable.


  if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {

   
$match = $db->query("SELECT * FROM users WHERE email='{$email}' AND password='{$password}' "); 
$data = mysqli_fetch_array($match); 
$user_id= $data['uid'];
$fname = $data['fname'];
$lname = $data['lname'];
$email = $data['email'];

if(mysqli_num_rows($match)==1){ //if there is such email and password.
$_SESSION['uid']=$user_id; //Storing user ID in SESSION variable.
$_SESSION['fname']=$fname; //Storing First name in SESSION variable.
$_SESSION['lname']=$lname; //Storing Last name in SESSION variable.
$_SESSION['email']=$email; //Storing EMAIL in SESSION variable.


$_SESSION['AutenUsera']=0; //SET TO FALSE.
if(($_SESSION['email']=$email) and ($_SESSION['password']=$password)){
$_SESSION['AutenUsera']=1; //SET TO TRUE.
echo "<meta http-equiv='refresh' content='0; index.php'>"; //if successful redirect to secured page
}

}
else
{
  $error='<div id="top-blurb-error">
            <span id="error-signing-in" >Oops!, Invalid email or password!</span>
          </div>';
// error message to display
}

  } else {
   $error=('<div id="top-blurb-error">
            <span id="error-signing-in" >Oops!, '.$email.' is not a valid email address !</span>
          </div>');
  }
 }
 
 $db->close();
}
// How to use this class
echo loginVal($db, $email, $password);
?>

8} How to extract Youtube url from post

On account of PHP group, things are minimal more less demanding than some time recently, with php pre_match function i could extact Youtube Videos from url from any client post to utilize it independently without affecting the orginal post.

Youtube API is use to retrieve the content of the video 'http://www.youtube.com/embed/'
PHP preg_match function is used to check if youtube url format is detect to capture link address.

Meanwhile you have to define your width-height.

<?php
$postdata ="THE SOCIAL NETWORK APP V.1.0 https://youtu.be/PGpbVQsVyRc Build Your Own Social Network"; // user post
 //if Youtube url detected;
if(preg_match('~(?:https?://)?(?:www.)?(?:youtube.com|youtu.be)/(?:watch\?v=)?([^\s]+)~', $postdata, $match)){
echo "
<iframe width='560' height='315' src='http://www.youtube.com/embed/".$match[1]."' frameborder='0' allowfullscreen></iframe>
";
//print ($match[1]); //url
}
else
{
echo $postdata;
}

?>

9} How to extract Vimeo url from post


Vimeo is also one of the popular video straming website avaliable so far, and lots of people are diving into it to publish their story and content, is nice to share memorie with familie and friends. if you are a developer working on your dreamed project or client website, that need this feature, then this is the perfect code for you, light weight and small in 

<?php
$message ="THE SOCIAL NETWORK APP V.1.0 https://vimeo.com/167653749 Build Your Own Social Network";
if(preg_match("/(https?:\/\/)?(www.)?(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/", $message, $output_array)) {
echo "<br>";

echo '<br><iframe width="600" height="400" src="//player.vimeo.com/video/'.$output_array[5].'?title=0&byline=0&portrait=0&color=ffffff" class="video"></iframe>';

    //echo "Vimeo ID: $output_array[5]"; //url
    }

?>

10} Instructions to separate @ and # symbol from string and how to change over text[url] to interactive connections


Creating clickable link with PHP is made easy, the function convert url to clickable link, this function support @ symbol and # tag enabled, for example like twitter or facebook @mention and hash # tag usage, you can implement this on your website or clients website. I have implemented this function On Thewallclone.com social system V3.0

<?php
function clickable_links($message)
{
  $parsedMessage = preg_replace(array('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))/', '/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '/(^|[^a-z0-9_])#([a-z0-9_]+)/i'), array('<a href="$1" target="_blank">$1</a>', '$1<a href="http://thewallclone.com/$2">@$2</a>',  '$1<a target="_blank" href="http://thewallclone.com/search.php?s=$2&searching=yes">#$2</a>'), $message);
  return $parsedMessage;
}
echo clickable_links($message);
?>

Trust postulations tips make a long keep running on your advancement profession... like, offer or hit me a remark simply say hello.... see you all around.


Previous Post
Next Post

post written by:

0 Comments:

Hit me with a comment!