I have a variable passed from a form via POST and want to know how to strip special characters from it before passing it to the mysql query. If anyone knows the function, please post.
php.net/mysql_real_escape_string Example#1 Simple mysql_real_escape_string() example <?php // Connect $link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password') OR die(mysql_error()); // Query $query = sprintf("SELECT * FROM users WHERE user='%s' AND password='%s'", mysql_real_escape_string($user), mysql_real_escape_string($password)); ?> PHP:
I had hoped to remove special characters prior to passing the variable to the mysql query. I tried str_replace but that still doesn't remove apostrophes or something that is part of php even when I tired to escape them with a backslash.
Do this: function cleanse($string) { $test = str_replace('"', '\"', strip_tags($string)); $test = escapeshellcmd($string); #the above statement should remove the ' but just to be on the safe side $test = ereg_replace("'", "", $string); return($test); } Code (markup):
The only way that worked is when I took everything out and just used: $string = ereg_replace("'", "", $string); PHP: was I wrong in not declaring a function?
could you please tell me what the regex /[^a-zA-Z0-9s]/ means? I know a little but am unsure about what this accomplishes. Thanks.
Basically it checks a variable for a certain condition. In this case regex is used to strip everything except alphanumeric characters and then stores the output back into $string.
Thanks for your help on this. Not sure what this means but I will try it: /^[a-z0-9][a-z0-9\-]+[a-z0-9]$/i I found it here: domain validation if anyone knows how to decode this into english, please post.
This matches a string with starts with one letter or number, then is followed by any number (>=1) of letters, numbers or hyphens, then ends with a letter or number. The /i makes it case insensitive, so the letters can be upper-case even though the regex was a-z and not a-zA-Z. So this would allow things like: abcde ab95 a------------------------bb----bbbbb--f-gd-gb---3 3fe but not allow: -9df ab 9 a.b As for your actual goal here, if you just want to safely store the string in the database, then mysql_real_escape_string() as initially suggested by jayshah is the correct answer. If, however, there is some other reason why you don't want any other characters in it, then indeed you need to pursue the regex business.