Top 10 PHP Code Snippets, You Can Not Miss

Professional PHP

PHP has created a lot of stir in the web development landscape, and it shows no clear signs of being supplanted. Being the most widely used scripting language available, PHP comes with a slew of exceptionally reliable code snippets that help developers to stay agile and productive. Thanks to its shallow learning curve, using these PHP code snippets, it’s possible for even the most novice web masters to create high quality projects with an utmost ease. With the help of these simple PHP snippets, they can start their work right off the bat and thus achieve effective results.

PHP-Code-Snippets

In this post, I have compiled a list of 10 PHP code snippets that come handy for any PHP developer. The snippets are resourceful to complete some specific range of tasks in an efficient manner. So, without much ado, let’s discuss about them in detail.

  1. Adjust Server Time

There are times when you see that your server time isn’t displayed correctly as per the local time. However, you can adjust it using the following code snippet.

$today = date(‘Y-m-d-G’);

$today = strftime(“%Y-%m-%d-%H”, strtotime(“$today -6 hour”));

If it’s 12 midnight according to your server, but it’s actually 5 pm, then adjust it within the $today variable by adding the difference of the total number of hours to get it displayed correctly.

  1. Create a Human Readable Random Script

Using the following code, you’ll be able to create a human readable string, resembling the look of dictionary words, which you may find useful for captchas.

/**************

*@length – length of random string (must be a multiple of 2)

**************/

function readable_random_string($length = 6){

$conso=array(“b”,”c”,”d”,”f”,”g”,”h”,”j”,”k”,”l”,

“m”,”n”,”p”,”r”,”s”,”t”,”v”,”w”,”x”,”y”,”z”);

$vocal=array(“a”,”e”,”i”,”o”,”u”);

$password=””;

srand ((double)microtime()*1000000);

$max = $length/2;

for($i=1; $i<=$max; $i++)

{

$password.=$conso[rand(0,19)];

$password.=$vocal[rand(0,4)];

}

return $password;

}

  1. Text Messaging with PHP Using the Text Magic API

Text Magic created a useful API that allows PHP developers to send messages to their clients with ease. For those who want to make use of API in their project, can get this paid service. Following is the code.

// Include the TextMagic PHP lib

require(‘textmagic-sms-api-php/TextMagicAPI.php’);

// Set the username and password information

$username = ‘myusername’;

$password = ‘mypassword’;

// Create a new instance of TM

$router = new TextMagicAPI(array(

‘username’ => $username,

‘password’ => $password

));

// Send a text message to ‘999-123-4567’

$result = $router->send(‘Wake up!’, array(9991234567), true);

// result: Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )

  1. Check Validity of Email Address

Using the snippet below you can easily check whether the concerned email address is valid or not.

<?php

$email_a = ‘John@example.com’;

$email_b = ‘bogus’;

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {

echo “This ($email_a) email address is considered valid.”;

}

if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {

echo “This ($email_b) email address is considered valid.”;

}

?>

  1. Display Source Code of Any Webpage

For those who want to display the source code of any webpage with line numbering, here is a simple code snippet that will do the job instantly.

<?php // display source code

$lines = file(‘http://google.com/’);

foreach ($lines as $line_num => $line) {

// loop thru each line and prepend line numbers

echo “Line #<b>{$line_num}</b> : ” . htmlspecialchars($line) . ”

\n”;

}

  1. Change Date from dd/mm/yyyy to yyyy-dd-mm

Use the following snippet to convert period-separated to slash separated or vice versa.

/**

* @param string $date (d.m.y, y-m-d, y/m/d)

* @return string|bol

*/

function convertDate($date) {

// EN-Date to GE-Date

if (strstr($date, “-“) || strstr($date, “/”))   {

$date = preg_split(“/[\/]|[-]+/”, $date);

$date = $date[2].”.”.$date[1].”.”.$date[0];

return $date;

}

// GE-Date to EN-Date

else if (strstr($date, “.”)) {

$date = preg_split(“[.]”, $date);

$date = $date[2].”-“.$date[1].”-“.$date[0];

return $date;

}

return false;

}

  1. Detect Location of a Specific IP

Below is a simple snippet that is useful to detect the location of a particular IP. The following function works by taking one parameter, and then returns the IP location. In the cases where no location is found, ‘unknown’ is returned.

function detect_city($ip) {

$default = ‘UNKNOWN’;

if (!is_string($ip) || strlen($ip) < 1 || $ip == ‘127.0.0.1’ || $ip == ‘localhost’)

$ip = ‘8.8.8.8’;

$curlopt_useragent = ‘Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)’;

$url = ‘http://ipinfodb.com/ip_locator.php?ip=’ . urlencode($ip);

$ch = curl_init();

$curl_opt = array(

CURLOPT_FOLLOWLOCATION => 1,

CURLOPT_HEADER     => 0,

CURLOPT_RETURNTRANSFER => 1,

CURLOPT_USERAGENT   => $curlopt_useragent,

CURLOPT_URL       => $url,

CURLOPT_TIMEOUT         => 1,

CURLOPT_REFERER         => ‘http://’ . $_SERVER[‘HTTP_HOST’],

);

curl_setopt_array($ch, $curl_opt);

$content = curl_exec($ch);

if (!is_null($curl_info)) {

$curl_info = curl_getinfo($ch);

}

curl_close($ch);

if ( preg_match(‘{<li>City : ([^<]*)</li>}i’, $content, $regs) ) {

$city = $regs[1];

}

if ( preg_match(‘{<li>State/Province : ([^<]*)</li>}i’, $content, $regs) ) {

$state = $regs[1];

}

if( $city!=” && $state!=” ){

$location = $city . ‘, ‘ . $state;

return $location;

}else{

return $default;

}

}

  1. Discover and Display Meta Tags

Information relating to meta tags can be displayed easily using the snippet below. Just alter the URL at the top of the code to change the website name from where the information has been gathered.

<?php $searchmeta1 = get_meta_tags(“http://example1website.com”); ?>

<?php $searchmeta2 = get_meta_tags(“http://example2website.com”); ?>

<!DOCTYPE html>

<html>

<head>

<meta charset=”utf-8″ />

<title>Meta Tag Finder</title>

<style>

*{

margin:0;

padding:0;

outline:0;

border:0;

}

html{min-height:100%; height:auto;}

body{

background:#FFF;

font-size:12px;

font-family:verdana, arial, sans-serif;

color:000;

}

a{

text-decoration:none;

color:#999;

}

a:hover{

color:#666;

}

#container{

width:900px;

margin:0 auto;

}

h1{

font-weight:bold;

font-size:20px;

text-align:center;

padding:14px;

letter-spacing:1.5;

font-family: georgia, Sans-Serif;

border-bottom:1px dashed #666;

margin-bottom:20px;

}

h2{

font-weight:normal;

font-size:16px;

padding-top:10px;

}

h3{

font-weight:boldl;

font-size:14px;

text-align:center;

padding-bottom:10px;

font-style:italic;

}

#left{

float:left;

width:430px;

padding-bottom:40px;

}

#right{

float:right;

width:430px;

padding-bottom:40px;

}

.box1{

display:block;

height:70px;

color:#FFF;

background-color:#EF810E;

margin:10px;

padding:10px;

border:1px solid #CF6B00;

border-radius:10px;

-moz-border-radius:10px;

-webkit-border-radius:10px;

box-shadow: 10px 10px 5px #888;

}

.box2{

display:block;

height:70px;

color:#FFF;

background-color:#5C66FF;

margin:10px;

padding:10px;

border:1px solid #3340CF;

border-radius:10px;

-moz-border-radius:10px;

-webkit-border-radius:10px;

}

</style>

</head>

<body>

<div id=”container”>

<h1>Meta Tag Finder</h1>

<div id=”left”>

<h3>NorthStar Media</h3>

<h2>Author:</h2>

<div class=”box1″>

<?php echo ($searchmeta1[“author”]); ?>

</div>

<h2>Copyright:</h2>

<div class=”box1″>

<?php echo ($searchmeta1[“copyright”]); ?>

</div>

<h2>Description:</h2>

<div class=”box1″>

<?php echo ($searchmeta1[“description”]); ?>

</div>

<h2>Keywords:</h2>

<div class=”box1″>

<?php echo ($searchmeta1[“keywords”]); ?>

</div>

<h2>Robots:</h2>

<div class=”box1″>

<?php echo ($searchmeta1[“robots”]); ?>

</div>

<h2>Generator:</h2>

<div class=”box1″>

<?php echo ($searchmeta1[“generator”]); ?>

</div>

</div>

<div id=”right”>

<h3>The Coupon Magazine</h3>

<h2>Author:</h2>

<div class=”box2″>

<?php echo ($searchmeta2[“author”]); ?>

</div>

<h2>Copyright:</h2>

<div class=”box2″>

<?php echo ($searchmeta2[“copyright”]); ?>

</div>

<h2>Description:</h2>

<div class=”box2″>

<?php echo ($searchmeta2[“description”]); ?>

</div>

<h2>Keywords:</h2>

<div class=”box2″>

<?php echo ($searchmeta2[“keywords”]); ?>

</div>

<h2>Robots:</h2>

<div class=”box2″>

<?php echo ($searchmeta2[“robots”]); ?>

</div>

<h2>Generator:</h2>

<div class=”box2″>

<?php echo ($searchmeta2[“generator”]); ?>

</div>

</div>

</div>

</body>

</html>

  1. Generating Data URI’s

Use the code below to create data URI’s. The snippet can be helpful for embedding images into HTML/CSS to save HTTp request.

function data_uri($file, $mime) {

$contents=file_get_contents($file);

$base64=base64_encode($contents);

echo “data:$mime;base64,$base64”;

}

  1. Identify Browser Language

The following code snippet can be used for detecting the browser language.

function get_client_language($availableLanguages, $default=’en’){

if (isset($_SERVER[‘HTTP_ACCEPT_LANGUAGE’])) {

$langs=explode(‘,’,$_SERVER[‘HTTP_ACCEPT_LANGUAGE’]);

foreach ($langs as $value){

$choice=substr($value,0,2);

if(in_array($choice, $availableLanguages)){

return $choice;

}

}

}

return $default;

}

That’s all! With this here is the end of the round up of 10 helpful PHP snippets for web developers. Use them to strengthen your skills. They come handy accomplish any task no matter how complicated they are.

About the Author:

Amanda Cline is a web developer who has helped companies gain momentum with their small and large scale projects. If you need to hire dedicated PHP developer then simply get in touch with Amanda via Twitter. she has also written interesting and informative articles on Custom Software Development, Web Application Development etc. She is currently working for Xicom Technologies Ltd, a leading Custom Web Development Company.

1 Comment

  1. RankGold says:

    I’m curious to find out what blog platform you are utilizing?
    I’m experiencing some small security issues with my latest
    blog and I would like to find something more safeguarded.
    Do you have any solutions?

Leave a Reply

Your email address will not be published. Required fields are marked *