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.