Sanitizing user input (PHP and MySql)

Sanitize database inputs

When inserting data in your database, you have to be really careful about SQL injections and other attempts to insert malicious data into the db. The function below is probably the most complete and efficient way to sanitize a string before using it with your database.

function cleanInput($input) {

  $search = array(
    '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments

    $output = preg_replace($search, '', $input);
    return $output;

function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    return $output;

Here’s some examples of use:

  $bad_string = "Hi! <script src=''></script> It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

  // Also use for getting POST/GET variables
  $_POST = sanitize($_POST);
  $_GET  = sanitize($_GET);



UI Developer Interview in inlogics – Chennai

I recently attended Interview in Inlogics for UI Developer position and got selected in this company.
I hope this post may help people to prepare for UI Devloper interviews.

The hiring process for experienced UI developer will be of three rounds. First one is easy level of technical interview, then second level will be a pure technical with Team Lead and then HR Round.
I attended first round in inlogics on feb 6th 2014 for exp UI Developer post. The interview was quite easy. Interviewer asked question in html5, css3 and jquery. Interview last for 30 to 40 mins. All are basic questions so anyone can clear.

CSS3 Questions asked:

1. Explain about css specificity

2. what is the use of box shadow and tell me the syntax.

3. how to acheive rounded corners in css3.

4. How will you improve the performance of a website.

5. What is the use of sprite images.

6. What are the different font formats and how will you include in your css stylesheet.

7. What is responsive web page layout.

8. What is fluid layout and advantages of it ?

9. What do you know about css animations. Will you do css3 animation if we give google access?

10. what are the css frameworks you know. have you ever used any css frameworks like LESS SAAS? 

HTML Questions


1. Difference between HTML4 and HTML5?

2. What is the use of canvas ? have you ever used it. 

3. What is the main difference between canvas and svg?

4. What are semantic tags in html5. What is the main advantage of it.


1. How will you add a jquery to your page.

2. What is the diiference between javascript and jquery?

3. Tell me the difference between document.ready and onload function in jquery?

4. how can u apply css in jquery?

5. Can you dynamicaaly add a div using jquery ?

6. What are filters in jquery?

7. What is an anonymous function in jquery and how will you define it?

6. Have you ever heared about MVC in javascript?

7. Javascript or Jquery which is faster ?

8. How can you animate using Jquery?

9. Tell me the use of is() , eq() methods in jquery?

10. Why we use index() method in jquery.

11. Tell me jquery.noConflict() method.

12. Have you ever contributed any plugin?

13. Tell me what are the Jquery UI you know. And how can you customize them.?

Handling broken image and replace with a default image for css background

Broken images will display nothing when their URL cannot be found. Instead we can replace it with a “default image” picture so that you are sure for a better visual.
We can use .error() function for this purpose.
The “error” event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.

So the HTML Markup as follows .

<div class="banner">
<img id="banner_image" src="image.png" />   

The Below javascript code will trigger an error when the image source is broken and it will load the default image.

         $J("#banner_image").error(function() {
         $J(this).attr('src', 'images/default.jpg')

Detect an broken CSS background-image and replace with a default image.

<div id="sub_ban" style="background-image:url('');"></div>

When the image has set as a css background we can do with ajax request.
The following javascript code will replace the broken css background image with default image

                var imageURLs = $('#sub_ban');
                imageURLs.each(function(index, element){
                    var imageURL = $(element).css('background-image').replace('url("', '').replace('")', '');
                    if (imageURL != "none"){
                            url: imageURL,
                            type: 'HEAD',
                            error: function(){
                               DefaultimageUrl = 'images/default.jpg';
                               $(element).css('background-image', 'url(' + DefaultimageUrl + ')');

Some usefull Functions in PHP

1.  This function is used to sanitize string for database security


function clean($str) {
  $str = @trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
return mysql_real_escape_string($str);

2. This function is used to generate random password.

function genPassword($length = 8) {
    $validCharacters = "abcdefghijklmnopqrstuxyvwzABCDEFGHIJKLMNOPQRSTUXYVWZ1234567890";
    $validCharNumber = strlen($validCharacters);

    $result = "";

    for ($i = 0; $i < $length; $i++) {
        $index = mt_rand(0, $validCharNumber - 1);
        $result .= $validCharacters[$index];

    return $result;

3. Function will return hyperlinks if we send url as a function parameter.

function urls_to_links($str) { 
    $pattern = '/((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))/is';
    $replace = '<a target="blank" href="$1">$1</a>';
    return preg_replace($pattern, $replace, $str);

4. This function is used to get the remote ip address

function getIpAddress()
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {   //check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!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;

5. This function is used to validate the Email Address.

function check_email($email)
    //check for vaild email
    if (eregi("^[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+(\.[a-z0-9,!#\$%&'\*\+/=\?\^_`\{\|}~-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.([a-z]{2,})$", $email)) {
           return $email;

    return false;

6. Function used to validate string

function string_only($str)
    if (ereg('^[A-Za-z_][A-Za-z_]*$', $str)) {
        return $str;
    return false;

7. Function to generate date range.

function dates_range($date1, $date2)
   if ($date1<$date2)
       while ($date1!=$date2)
           $date1=mktime(0, 0, 0, date("m", $date1), date("d", $date1)+1, date("Y", $date1));
           $dates_range[]=date('Y-m-d', $date1);
   return $dates_range;

echo '<pre>';
print_r(dates_range('2013-11-25', '2013-11-30'));
echo '</pre>';

It will output something like…

    [0] => 2013-11-25
    [1] => 2013-11-26
    [2] => 2013-11-27
    [3] => 2013-11-28
    [4] => 2013-11-29
    [5] => 2013-11-30

Case sensitive String Comparison in MySql Table

Usually the MySql Queries are Case insensitive. The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE ‘a%’, you get all column values that start with A or a.

This can be performed with mysql query . For this you have to use .

SELECT * FROM `table` WHERE BINARY `column` = 'value';

To acheive this in phpmyadmin , you can change the language collation to latin1_general_cs
If you want a column always to be treated in case-sensitive fashion, declare it with a case sensitive or binary collation.

Example :

SELECT * FROM users_table;

id first_name Email
1 mahran
2 John
3 john
4 Gill NULL

4 rows in set (0.001 sec)

SELECT * FROM users_table WHERE `first_name` ='John';
id first_name Email
1 John
2 john

2 rows in set (0.00 sec)

SELECT * FROM users_table WHERE BINARY `first_name` ='John';

id first_name Email
1 John

1 rows in set (0.00 sec)

Error Reporting in PHP

To enable error reporting , add the following lines to the top of your script.

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
ini_set('display_errors', 1);

error_reporting function is used to report different types of PHP errrors.
We can pass different parameters to the function error_reporting.
We use these four major parameters to get the information about the error.

E_ERROR  – This is Fatal run-time errors. These indicate errors that can not be recovered , such as a memory allocation problem. Execution of the program will be stopped.
E_WARNING  – Run time warnings. Execution of the program will be stopped.
E_PARSE (integer) – This function will report Compile-time parse errors. Parse errors should only be generated by the parser.
E_NOTICE (integer) – Used to report Run-time notices. Eg. This function is used to report uninitialized variables in the program.

To turn off all the Errors you can simply use


at the top of your php file.
Make sure that your php.ini file sets error reporting to E_ALL to output errors .

Function to convert decimal to fraction php

This is a simple function which is use to convert decimal to fraction in php.
The code for the function is given below.

 function toFraction($number) {
 $numerator = 1;
 $denominator = 0;
 for(; $numerator < 1000; $numerator++) {
 $temp = $numerator / $number;
 if(ceil($temp) - $temp == 0) {
 $denominator = $temp;
 $a = ($denominator > 0) ? $numerator . '/' . $denominator : false;
 $c = explode("/",$a);
 list($n, $w) = $c;
 if ($w == 1) {
 return $n /$w ;
 } else {
 return ($denominator > 0) ? $numerator . '/' . $denominator : false;
 echo toFraction(7.5);

Output :

In the above function i have passed a decimal value .
The result will be the fraction form of the input.