Top 10 Best PHP Snippets Coding Magics

Hello, Today I am going to provide you the best top 10 PHP coding magics which really works great.  PHP coding can help an user to work easily and its so beneficial theses days. So here I am providing you the top 10 best PHP coding.

10 Best PHP Coding Magics are :

1. Unzip a Zip File :

<?php $zip = new ZipArchive; $res = $zip->open(’my_zip_file.zip’); if ($res === TRUE) { $zip->extractTo(’my_extract_to_dir/’); $zip->close(); echo ‘ok’; } else { echo ‘failed’; }?>

2Date format validation in PHP :

Validate a date in “YYYY-MM-DD” format.

function checkDateFormat($date) {//match the format of the dateif (preg_match (“/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/”, $date, $parts)) {//check weather the date is valid of not if(checkdate($parts[2],$parts[3],$parts[1])) return true; else return false; } else return false; }

 3. Creating and Parsing JSON data in PHP :

To handle JSON data there is JSON extension in PHP which is aviable after PHP 5.2.0. Two funcitons : json_encode() and json_decode() are very useful converting and parsing JSON data through PHP.
First of all, let’s look at the PHP code to create the JSON data format of above example using array of PHP.

$json_data = array (‘id’=>1,’name’=>”mike”,’country’=>’usa’,”office”=>array(“microsoft”,”oracle”)); echo json_encode($json_data);

The above code generates the JSON data exactly as above. Now, let’s decode above JSON data in PHP.

$json_string=’{“id”:1,”name”:”mike”,”country”:”usa”,”office”:["microsoft","oracle"]} ‘; $obj=json_decode($json_string);

Now, the $obj variable contains JSON data parsed in PHP object which you can display using code below.

echo $obj->name; //displays mike
echo $obj->office[0]; //displays microsoft
As you can guess,$obj->office is an array and you can loop through it using foreach loop of PHP,
foreach($obj->office as $val)
echo $val;

4. Database Connection in PHP :

If you want to use a database in your application, you have to make config.php file which will contain basic database data. Here we will declare database path, username, password, database name and create connection string. We’ll make local database connection for a start. Put the code below into config.php file and put it in the root folder of your project.

<?php$host = “localhost”; //database location$user = “bitis”; //database username$pass = “kaka”; //database password$db_name = “bitis”; //database name//database connection$link = mysql_connect($host, $user, $pass); mysql_select_db($db_name);?>

First 4 lines are basic database data. 2 lines below is connection string which connects to server and then mysql_select_db selects database.
To include config.php into  website simply put next line on the top of the source code of index.php.
<?php include ‘config.php’; ?>

5Parsing XML in easy way using PHP :

Required Extension: SimpleXML

//this is a sample xml string$xml_string=”<?xml version=’1.0′?> <moleculedb> <molecule name=’Alanine’> <symbol>ala</symbol> <code>A</code> </molecule> <molecule name=’Lysine’> <symbol>lys</symbol> <code>K</code> </molecule> </moleculedb>”;//load the xml string using simplexml function$xml = simplexml_load_string($xml_string);//loop through the each node of moleculeforeach ($xml->molecule as $record) { //attribute are accessted byecho $record['name'], ‘  ‘;//node are accessted by -> operator echo $record->symbol, ‘  ‘; echo $record->code, ‘<br />’; }

As you see the above string is parsed using simplexml_load_string() function and the data are stored in the formed of array object of SimpleElement. After that, the array element is displayed by using foreach() loop of PHP. Here is the output of the code.

Alanine ala A
Lysine lys K

6Email validation snippet in PHP :

$email = $_POST['email']; if(preg_match(“~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~”,$email)) { echo ‘This is a valid email.’; }
else{ echo ‘This is an invalid email.’; }

7.  Seconds to String :

This function will return the duration of the given time period in days, hours, minutes and seconds.
e.g. secsToStr(1234567) would return “14 days, 6 hours, 56 minutes, 7 seconds”

function secsToStr($secs) { if($secs>=86400){$days=floor($secs/86400);$secs=$secs%86400;$r=$days.’ day’;if($days1){$r.=’s’;}if($secs>0){$r.=’, ‘;}} if($secs>=3600){$hours=floor($secs/3600);$secs=$secs%3600;$r.=$hours.’ hour’;if($hours1){$r.=’s’;}if($secs>0){$r.=’, ‘;}} 4 if($secs>=60){$minutes=floor($secs/60);$secs=$secs%60;$r.=$minutes.’ minute’;if($minutes1){$r.=’s’;}if($secs>0){$r.=’, ‘;}} $r.=$secs.’ second’;if($secs1){$r.=’s’;} return $r; }

 8. Get Remote IP Address in PHP :

function getRemoteIPAddress(){ $ip = $_SERVER['REMOTE_ADDR']; return $ip; }If you’re behind a proxy server, use the following code to get the real IP of client:function getRealIPAddr() { if (!empty($_SERVER['HTTP_CLIENT_IP'])) //check ip from share internet { $ip=$_SERVER['HTTP_CLIENT_IP']; } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) //to check ip is pass from proxy { $ip=$_SERVER['HTTP_X_FORWARDED_FOR']; } else { $ip=$_SERVER['REMOTE_ADDR']; } return $ip; }

9. Base64 Encode and Decode String in 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; }

10. Send Mail using mail function in PHP

<?php// Your email address$email = “you@example.com”;// The subject$subject = “Enter your subject here”;// The message$message = “Enter your message here”;mail($email, $subject, $message, “From: $email”);echo “The email has been sent.”;?>

About Amar Ryder

Amar Ryder has written 116 post in this blog.

I am Amar Ryder, 18yr Old Passionate Blogger and Site designer.I am keen to learning Social Media and Internet Marketing

Join Our Newsletter

Join over to get free and fresh content delivered automatically each time we publish.

The Discussion

  1. It’s a really very informative information. It’s very useful and knowledgeable for me.i was stuck while coding this. I will bookmark this page for coding help.

Speak Your Mind

*

CommentLuv badge