Jump to content

[SOLVED] the input-cleaning function to end them all... suggestions?


alexweber15

Recommended Posts

this is what i usually but im sure theres better ways of doing it:

 

function clean(&$val){
    trim(strip_tags(htmlspecialchars($val)));
}

 

im sure addslashes() or mysql_real_escape_string() should be there somewhere but im not sure...

 

someone comment please? :)

 

-Alex

IMHO, there's no need to use strip tags AND htmlspecialchars()

 

Try:

 

function clean($string){

//See if magic quotes is turned on. I hate magic quotes and so should you.
if(get_magic_quotes_gpc() == 1){
	$string = stripslashes($string); //get rid of nasty slashes if magic quotes are on
}
$string = htmlentities($string,ENT_QUOTES,"utf-8"); //convert input into friendly characters to stop XSS
$string = mysql_real_escape_string($string); //stop h4x0r from putting SQL in
return $string; //return a lovely clean string that you could bring home to your mother
}

 

I'd personally create a recursive function to clean entire arrays (even arrays of arrays and such):

<?php
function clean_recursive($value) {
if (is_array($value)) {
	foreach($value as $k=>$v) {
		$value[$k] = clean_recursive($v);
	}
}
else {
	if(get_magic_quotes_gpc() == 1){
		$value = stripslashes($value);
	}

	$value = htmlentities($value,ENT_QUOTES,"utf-8"); //convert input into friendly characters to stop XSS
	$value = mysql_real_escape_string($value);
}
return $value;
}
$do = clean_recursive(array('somet"h"\'in"g', 'lol"', array('l\'ol')));
print_r($do);

 

Tested and works.

Yeah, you might as well use trim().  And htmlentities() changes more characters than htmlspecialchars().

 

so this is what the new uber function looks like:

 

<?php
function clean_recursive($value) {
   if (is_array($value)) {
      foreach($value as $k=>$v) {
         $value[$k] = clean_recursive($v);
      }
   }
   else {
      if(get_magic_quotes_gpc() == 1){
         $value = stripslashes($value);
      }

      $value = trim(htmlspecialchars($value,ENT_QUOTES,"utf-8")); //convert input into friendly characters to stop XSS
      $value = mysql_real_escape_string($value);
   }
   return $value;
}
//test
$do = clean_recursive(array('somet"h"\'in"g', 'lol"', array('l\'ol')));
print_r($do);

 

any objections?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.