Jump to content

Check for invalid characters..


rockinaway

Recommended Posts

Do you not want to put in the charactors at all?? Or you just want to make sure the queries work??

 

I am not that good with preg_match or regex so maybe someone will help with that. But if you just want to make sure the query will run if someone has special charactors, you can just use mysql_real_escape_string() to prepare the data for insert.

 

Ray

Yeah, the normal usage is:

 

<?php
  $field1 = mysql_real_escape_string($_POST['field1']);
  $field2 = mysql_real_escape_string($_POST['field2']);
  //etc
  mysql_query("INSERT INTO tablename (field1,field2) VALUES ('{$field1}','{$field2}')");
?>

If you want to remove the invalid characters, then you would do something like...

 

<?php

  function clean_it($input) {
    return $output = trim(preg_replace('/[^aA-zZ0-9]/','',$input));
  }

?>

 

BUt I guess I'm wondering if you want to strip out certain characters...or just escape the string/input.

Did you want to create a whitelist or a blacklist? Usually the most effective method it to have a white list, and use regex to find anything that isn't in it.

 

the nice part about regex is you can use character ranges.... IE if you want to allow letters, numbers, hyphens and underscores, you would do this:

 

<?php
$whitelist = 'a-z0-9\-_]';

$regex = '/[^'.$whitelist.']/i';

if (preg_match($regex, $subject) ) {
    echo 'Bad character detected!';
}
?>

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.