Saturday, December 28, 2013

Using JSON in PHP

JSON (JavaScript Object Notation) is a standard format used to transmit data between a server and a web application. It is an alternative to XML. JSON string is a human-readable text consisting of attribute-value pairs. JSON is a language-independent data format and many languages support generating and parsing JSON data.

The following is the format of the JSON string:
{
                “first_name” : “Barack”,
                “last_name” : “Obama”,
                “address” :{
                                “city” : “Washington, DC”,
                                “country” : “United States of America”
},
“phone_numbers” : [
{
                “type” : ”home”,
                “number” : ”000 000-0000”
},
{
                “type” : ”office”,
                “number” : ”000 000-1111”
}
                ]
}

PHP 5.2.0 supports JSON by default and we do not need any additional installation and configuration to use JSON. If the PHP version is less than 5.2.0, we need to install JSON PECL extension and guide for installation of PECL extensions can be found at the official PHP website php.net.
There are three functions in PHP to support JSON. They are json_encode, json_decode, and json_last_error. json_decode function converts JSON string into PHP variable to use that data for further programming.  If the JSON string cannot be decoded then null will be returned.

PHP json_encode() function coverts a PHP value into a JSON string. For example, from a PHP array, it can create a JSON representation of that array.

The following is the simple PHP script that uses JSON:
<?php
//Array creation
$arr=array('PHP','MySQL','Javascript');
//Encoding the array to JSON string
$json=json_encode($arr);
echo $json;
//Decoding the JSON string back to array.
$decode=json_decode($json);
echo "<br>";
echo $decode[0];

?>

Friday, December 27, 2013

Inline vs Block elements in CSS

Most of the HTML elements have default value for display property in CSS as block or inline

The elements with default value of display property as block include <div>, <p>, <h1> to <h6>, <form> etc. The elements with this display type have the following characteristics:
  • Height, line-height, and top and bottom margins can be changed.
  • Always begin on a new line.
  • Width is 100% unless a width is specified.

The elements with default value of display property as inline include <span>, <a>, <img>, <input> etc. The elements with this display type have the following characteristics:
  • Height, line-height and top and bottom margins cannot be changed. 
  • Begin on the same line 
  • Width is based on the text/image and it cannot be changed.

The characteristics mentioned above of an element can be  changed by setting the CSS property of the element as display: inline or display: block. By changing this property value we can do achieve many options like:
  • Have a block element start on the same line 
  • Have an inline element start on a new line 
  • Change the width and height of an inline element. 

The following is the sample CSS code to make a link look like a button with 100px width:
 
a{
color:white;
text-decoration:none;
background:#00f;
padding:10px;
width:100px;
margin:10px;
text-align:center;
display:block;
}

If we remove the display:block property from the above code, the width and margin of the link cannot be modified.

Monday, December 23, 2013

Storing passwords safely in database using PHP and MySQL

Passwords of the users registered with our site should be stored as plain text, because if someone gets access to the database he will be getting the passwords of all the users.  Many people use the same password for different websites and therefore those accounts will be compromised as well. Therefore we need use some type of encryption to store passwords in the database.

Simple encryption algorithms are reversible and therefore if we use simple encryption technique to encrypt the password, the original password can be generated from the encrypted one.

Cryptographic hashing functions such as MD5 are irreversible, which makes it difficult to get the original password from the encrypted one. To validate the use at login we need to again encrypt the user entered password with MD5 and compare it with the password stored in the database at the time of user registration. The following is the code to hash the password with MD5.

<?php
$password = 'mypassword';
$hash = md5($password);
?>

It is impossible to retrieve the original password from the hashed passowd. If a user forgets his password, we need to simply generate a new one.

It is quite possible for someone to make a list of millions of hashed passwords (rainbow table) and compare the hashes to find the original passwords. Therefore the intruder can  find the original password if we use MD5. The same applies for other hashing functions like SHA-1. This hashes are also prone to brute forcing (trying out all combinations with an automated script). 

We can use a salt to encrypt the password. A salt is a string that is hashed together with the password and therefore one cannot get the original password by comparing the hashed password with the rainbow tables. The following is the code to hash the password using a salt.

<?php
$password = 'mypassword';
$salt = '12345';
$hash = md5($salt . $password);
?>

To validate the use on login we have to hash the user entered password using the same salt and compare it with password stored in the database.

Some additional tips to secure user accounts passwords are:

Limit the number of failed login attempts.
Minimum length of the password should be at least 8 characters or more.

Allow or even make mandatory to use special characters in passwords.

Friday, December 20, 2013

Sending Email through PHP

Sending email though PHP is very easy using the PHP function mail(). But we have to append the email headers for adding options like adding CC (carbon copy) and BCC (Behind Carbon Copy). The following is the code to send Email with different options.

<?php 
//Message to be send
$message = "Hi, This is a sample mail send through PHP using additional headers .";
//Subject of the message
$subject = "Test mail";

//Adding from email ID. This is required.
$headers = "From: $from\r\n";

//If the email has HTML content the following lines needs to be added to header. This is optional.
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

//If the email has different reply to email other than the from email ID.  This is optional.
$headers .= "Reply-To: $replyto\r\n";

//To send a CC of this email to another email ID. This is optional. If we want to send CC to more than one email ID, we have to add multiple email ids separated by after Cc:
$headers .= "Cc: $cc_mailid \r\n";

//To send a BCC of this email to another email ID. This is optional. If we want to send BCC to more than one email ID, we have to add multiple email ids separated by after Bcc:
$headers .= "Bcc: $bcc_mailid \r\n";

//Finally, to the send the email with the above options.
If  (mail($to, $subject, $message, $headers)
                echo "Email send successfully.";
else
                echo "There was an error while send the email.";
?>

Note: The above program will only work if your server is properly configured for e-mail.  Therefore this program may not work in your local installation. Some web servers may have the email server hosted on another machine.


Thursday, December 19, 2013

Getting content from a webpage in PHP using CURL

We can get content from a website in PHP using PHP function file_get_contents(). Below is the sample code to display the content from a website.

<?php
$content=file_get_contents('http://www.example.com');
echo $content;
?>

But some website does not allow accessing their content by anything other than web browser. Such websites block the program that is trying to access their content by checking for a User Agent string, which is sent by all browsers to websites they visit. Therefore to access this type of websites, we have to write a program that simulates being a browser. In this tutorial we will learn how to write a program that fetches the content of a web page simulating like a browser.  For this program, we use the Mod CURL (Client URL) library extension to PHP.  It only works when this extension is enabled in our server or PHP installation.

The following is an example User Agent string:
Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201
For more information and list of User Agent string you can visit www.useragentstring.com

The following is the code to get content from a website using CURL:

<?php
$url='http://www.example.org';
$user_agent='Mozilla/5.0 (Windows; U; Windows NT 6.1; rv:2.2) Gecko/20110201';

$curl=curl_init(); //Open a session using CURL

//Setting options for CURL
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_FAILONERROR, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 8);
curl_setopt($curl, CURLOPT_TIMEOUT, 8);

$content=curl_exec($curl); //Executing the CURL
curl_close($curl); //Close session

echo $content;
?>

Note: Some websites only allow browsers to access their web pages because other programs are not permitted to access it. So please check whether you are allowed to access the content of a website before using this code to access that website.

Wednesday, December 18, 2013

Data Validation and Sanitizing with PHP

To make website secure and protect them from hacks and preventing bad guys from gaining access to our site’s data, it is very important to validate and sanitize data from external sources before performing any action on those data. Validation is the process of verifying whether the data is in the format what we expect. Sanitization is the process to remove unwanted characters or malicious code from the data. We cannot trust any data we collect from external sources like user submitted data. We need to first validate the data and then sanitize it before displaying it or inserting it into database.

When users submit data to our website, we need to make sure that the data is the form we expect. If we expect the input to be an integer we need to validate that the input user has submitted is an integer. In the same we way we need to validate data the user enters for other types like name should only contain alphabets and period, email should contain only alphanumeric characters, at the rate, underscore and period. If the field shouldn't have HTML in it, we need to make sure to remove HTML from it. If the field should have HTML in it, make sure only the parts of HTML that we like are included. The following are some of the simple methods to validate user submitted data:

Numbers Only

The following code will validate numbers. It will take a value and strip out any non-numeric characters. This code will allow negative numbers and decimal points.

$output = preg_replace("/[^0-9\-.]/", "", $data);

Strip Tags or Display Tags

To remove HTML tags from the data we can use the following PHP function.

$output = strip_tags($data);


If we want to display HTML tags in the output we can use the following PHP function. This function displays the HTML tags, the code will not be parsed.

$output = htmlspecialchars($data);

Escaping Strings in MySQL

The following functions can be used to sanitize the data before it can be inserted into database.

<?php
function clean_data($data) {

  $filters = array(
    '@<script[^>]*?>.*?</script>@si',   // Remove javascript code
    '@<[\/\!]*?[^<>]*?>@si',            // Remove HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Remove style tags
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Remove multi-line comments
  );

    $output_data = preg_replace($filters, '', $data);
    return $output_data;
  }


function sanitize_data($data) {
    if (is_array($data)) {
        foreach($data as $key=>$val) {
            $output_data[$key] = sanitize_data($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $data = stripslashes($data);
        }
        $data  = clean_data($data);
        $output_data = mysql_real_escape_string($data);
    }
    return $output_data;
}
?>

The following is the usage example of the above functions.

<?php
  $string = "This is my <script src='http://www.example.com/malicious_script.js'></script> profile.";
  $output_string = sanitize_data($string);

echo "Original String : ".$string;
echo "<br> Sanitized String : ".$output_string;
?>


If you run the above script and see the generate output using view source from the browser, you can see that the input string has the javascript embedded in it, which the output string does not contain it.

Generating thumbnail for an image using PHP

This is a basic tutorial for beginners. In this tutorial we are going to learn how to generate a thumbnail from an image. We are going to write a simple function, which would convert any image (gif, jpg or png) into thumbnail. This function creates the thumbnail image from the source image. The actual weight and height of the thumbnail are calculated based the proportional values of the source image width and height respectively.

The following is the code:

<?php
// Function for resizing jpg, gif, and png image files

function image_resize($original, $thumb, $w, $h, $ext) {
    list($w_org, $h_org) = getimagesize($original);
    $scale_ratio = $w_org / $h_org;
    if (($w / $h) > $scale_ratio) {
           $w = $h * $scale_ratio;

    } else {
           $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    
if ($ext == "gif"){ 
      $img = imagecreatefromgif($original);
    } else if($ext =="png"){ 
      $img = imagecreatefrompng($original);
    } else if($ext =="jpg" or $ext =="jpeg"){ 
      $img = imagecreatefromjpeg($original);
    }else{
  echo "Only images of type jpg, gif and png are supported.";
  exit;
}
    $true_img = imagecreatetruecolor($w, $h);
    imagecopyresampled($true_img, $img, 0, 0, 0, 0, $w, $h, $w_org, $h_org);
    imagejpeg($true_img, $thumb, 80);
}


$file_name = "sample.gif"; // name of the source image file
$arr = explode(".", $file_name); // Split file name into an array
$fileExt = end($arr); // Get the file extension from the array's last element

$thumb = "thumb_$fileName"; // name of the thumb to be generated 
$width = 100; // maximum width of the thumbnail to be created
$height = 100; // maximum height of the thumbnail to be created

image_resize($file_name, $thumb, $width, $height, $fileExt); //Call image resize function

//Display original image
echo "Originaal Image: <br/>";
echo "<img src='$file_name'><br/><br/>";

//Display image thumbnail generated
echo "Thumb Image: <br/>";
echo "<img src='$thumb'>";
?>

Tuesday, December 17, 2013

Generating Excel files using PHP

In this tutorial we will be learning how to generate a basic excel file using PHP without using any third party libraries. For generating excel sheets with styling, we need to use other libraries.

The following are the functions, which you can write in your main PHP file or in an external file and include it in your main file.

<?php 
// Function to generate Excel File header 
function xlsBOF() { 
    echo 
pack("ssssss"0x8090x80x00x100x00x0);  
    return; 
} 

// Function to generate Excel File Footer 
function xlsEOF() { 
    echo 
pack("ss"0x0A0x00); 
    return; 
} 

// Function to write a Number (double) into a Cell in Excel
function xlsWriteNumber($Row$Col$Value) { 
    echo 
pack("sssss"0x20314$Row$Col0x0); 
    echo 
pack("d"$Value); 
    return; 
} 

// Function to write a label (text) into Cell in Excel 
function xlsWriteLabel($Row$Col$Value ) { 
    
$L strlen($Value); 
    echo 
pack("ssssss"0x204$L$Row$Col0x0$L); 
    echo 
$Value; 
return; 
} 
?> 

The following is the code to generate excel file.

<?php 
// Headers to inform browser that the file is excel
header 
("Expires: "gmdate("D,d M YH:i:s") . " GMT"); 
header ("Last-Modified: " gmdate("D,d M YH:i:s") . " GMT"); 
header ("Cache-Control: no-cache, must-revalidate");     
header ("Pragma: no-cache");     
header ('Content-type: application/x-msexcel'); 
header ("Content-Disposition: attachment; filename=Sample.xls" );  
header ("Content-Description: PHP/INTERBASE Generated Data" ); 
// 
// the following is the code to add content to the Excel stream 
// 
xlsBOF();   // begin Excel file 
xlsWriteLabel(0,0,"This is a label");  // write a text in A1 cell  (row 1, column 1) 
xlsWriteNumber(0,1,9999);  // write a number in B1 cell (row 1, column 2) 
xlsEOF(); // end of Excel file 
?>

This is the simplest and easiest way to generate Excel file in PHP. As mentioned at the beginning of this tutorial, to generate more complex Excel files with styling and other formatting, you need to use other libraries.