Function to protect your code from injections (easy to use)

A

Anonymous

Guest
Hey guys I want to share a function to clear everything harmful someone can write in to your textfields and areas. *NOTE: FOR MYSQLI!*
For example I save two variables that I will call

$username
$password

First step: Add this before you are inserting this variable to a database or using any sql connections with it
Code:
function cleanInput($input) {
 
  $search = array(
    '@<script[^>]*?>.*?</script>@si',  
    '@<[\/\!]*?[^<>]*?>@si',           
    '@<style[^>]*?>.*?</style>@siU',   
    '@<![\s\S]*?--[ \t\n\r]*>@'       
  );
 
    $output = preg_replace($search, '', $input);
    return $output;
  }
Step 2:
After I added this only thing I need is to run my variable through this function:

Code:
$var = trim(cleanInput(mysqli_real_escape_string($con,$var)));

In my case this would look like this

Code:
$username = trim(cleanInput(mysqli_real_escape_string($con,$username)));
$password = trim(cleanInput(mysqli_real_escape_string($con,$password)));



Sum:

Add this to your PHP code:
Code:
function cleanInput($input) {
 
  $search = array(
    '@<script[^>]*?>.*?</script>@si',  
    '@<[\/\!]*?[^<>]*?>@si',           
    '@<style[^>]*?>.*?</style>@siU',   
    '@<![\s\S]*?--[ \t\n\r]*>@'       
  );
 
    $output = preg_replace($search, '', $input);
    return $output;
  }

After that run your variable through it:
Code:
$YOURVARIABLE = trim(cleanInput(mysqli_real_escape_string($con,$YOURVARIABLE)));

I hope you enjoy this code :)
 
Sorry, but I wouldn't touch that script with a ten foot pole, for using regex to cleanup "injections" in my opinion is a bad idea. One can not possibly know the possible number combinations a user can enter, unless you're some kind of egghead from MIT. Your better using prepared statements or simply using htmlspecialchars if you want to sanitize the user's OUTPUT.

You could even get fancy by doing the following:
Code:
function html_escape($raw_input)
{
    // important! don"t forget to specify ENT_QUOTES and the correct encoding
  return htmlspecialchars($raw_input, ENT_QUOTES | ENT_HTML5, "UTF-8");
}
However, I'm more in favor of using prepared statements with MySQL.
 
Well learn some better PHP and get your function work ;). You could of course add some functions as htmlspecial chars and run variable through it after my function
 
Back
Top