Sanitize User Input


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  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);

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.