PHP Sanitize Database Input

Aug 27, 2013, by admin

Hi all today we are going to see how to sanitize and clean all incoming user data that is going to be used in a database because we can’t trust all users. Here I am going to share a function which sanitize all input data and remove the chances of code injection.

Function For Cleaning Input Data :

  1. <?php
  2. function sanitize_input_data($input_data) {
  3. $input_data = trim(htmlentities(strip_tags($input_data,“,”)));
  4. if (get_magic_quotes_gpc())
  5. $input_data = stripslashes($input_data);
  6. $input_data = mysql_real_escape_string($input_data);
  7. return $input_data;
  8. }
  9. ?>

Usage of sanitize_input_data function:

  1. <?php
  2. $bad_string = “Hi! <script src=’http://www.evilssite.com/bad_script.js’></script> It’s a good day!”;
  3. $good_string = sanitize_input_data($bad_string);
  4. echo $good_string;
  5. //OUTPUT:: Hi! It’s a good day!
  6. ?>

Hope this post will be useful for you to get more updates like the page Bugtreat Technologies