Free PHP Code

Posted by Marxman in Articles, PHP, Programming

Looking  useful php codes? . Here’s a list of 12 absolutely essential PHP code snippets.

1. Send Mail using mail function in PHP


// Your email address

$email = “”;

// 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.”;


2. 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;

3. Get Remote IP Address in PHP

function getRemoteIPAddress()

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
else if (!empty($_SERVER[‘HTTP_X_FORWARDED_FOR’])) //to check ip is pass from proxy
return $ip;

4. 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;

5. Email 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.';


echo ‘This is an invalid email.';

6. Parsing XML in easy way using PHP

Required Extension: SimpleXML

//this is a sample xml string
$xml_string=”<?xml version=’1.0’?>
<molecule name=’Alanine’>
<molecule name=’Lysine’>

//load the xml string using simplexml function
$xml = simplexml_load_string($xml_string);

//loop through the each node of molecule
foreach ($xml->molecule as $record)

//attribute are accessted by
echo $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

7. 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.

$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);


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'; ?>

8. 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”]} ‘;

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;

9. Date format validation in PHP

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

function checkDateFormat($date)

//match the format of the date
if (preg_match (“/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/”, $date, $parts))

//check weather the date is valid of not
return true;
return false;
return false;

In the above function, first of all format of date is validated using regular expression. As you can see the in the preg_match() function, there are three expression each separated by “-” and there can be only digits of length of 4,2 and 2 in these expressions. If the date format is incorrect then this function returns “false” value. And, if the supplied string contains the valid date format then the part matching each expression are stored in the “$parts” array. Such as, if we supply “2007-03-12? then “2007?, “03? and “12? are stored in the “$parts” array. After that, checkdate() function of PHP is used check weather the supplied date is valid date or not.

10. PHP Redirect Script

header( ‘Location:’ ) ;

Change the code on the redirect page to be simply this. You need to replace the URL above with the URL you wish to direct to.

11. Directory Listing in PHP

1.  Define the Path which you want to have the directory displayed and save it as a variable.
2. Use the @opendir() function to define the array.
3. Run a while loop to read everything from the array.
4. Display the results and set them up like links.
5. Close the array.

//define the path as relative
$path = “/home/yoursite/public_html/whatever”;

//using the opendir function
$dir_handle = @opendir($path) or die(“Unable to open $path”);

echo “Directory Listing of $path<br/>”;

//running the while loop
while ($file = readdir($dir_handle))
echo “<a href=’$file’>$file</a><br/>”;

//closing the directory


12. Unzip a Zip File


$zip = new ZipArchive;

$res = $zip->open(’’);

if ($res === TRUE) {



echo ‘ok’;

} else {

echo ‘failed’;



Basically it extracts the zip file into the directory you specify… make sure

the directory you want to extract it to has write permissions

This is guest post from Marxman at