Posted By

gabrielsmith on 10/19/09


Tagged

input user


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

mgerdt
StevenW721


Sanitize User Input


 / Published in: PHP
 

URL: http://www.denhamcoote.com/php-howto-sanitize-database-inputs

  1. function cleanInput($input) {
  2.  
  3. $search = array(
  4. '@<script[^>]*?>.*?</script>@si', // Strip out javascript
  5. '@<[\/\!]*?[^<>]*?>@si', // Strip out HTML tags
  6. '@<style[^>]*?>.*?</style>@siU', // Strip style tags properly
  7. '@<![\s\S]*?--[ \t\n\r]*>@' // Strip multi-line comments
  8. );
  9.  
  10. $output = preg_replace($search, '', $input);
  11. return $output;
  12. }
  13.  
  14. function sanitize($input) {
  15. if (is_array($input)) {
  16. foreach($input as $var=>$val) {
  17. $output[$var] = sanitize($val);
  18. }
  19. }
  20. else {
  21. $input = stripslashes($input);
  22. }
  23. $input = cleanInput($input);
  24. $output = mysql_real_escape_string($input);
  25. }
  26. return $output;
  27. }
  28.  
  29. //usage
  30. $bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!";
  31.  
  32. $_POST = sanitize($_POST);
  33. $_GET = sanitize($_GET);
  34. $good_string = sanitize($bad_string);

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: StevenW721 on February 3, 2011

Love this snippet, thanks for posting! One small comment though, does this really need two functions? I'd say it'd be much cleaner and more portable if you combined the two into one sanitize function. Just my $.02

You need to login to post a comment.