MySQL prep makes user input safe to use in SQL queries. MySQL prep should be used whenever user input is piped directly into the SQL query to prevent SQL Injection.
The code below is written in Perl but the same concepts apply to any language.
The code does the following:
Removes whitespace at the beginning and end of the string.
Replaces backslashes (\) with double backslash (\\).
Replaces single quotes (') with backslashed single quote (\').
Replaces percent signs (%) with backslashed percent signs (\%) to prevent wildcard errors with MySQL.
Removes all charactors that are not alpha-numeric, whitespace, or special charactors.
sub mysqlprep {
local ($string) = @_;
$string =~ s/^\s+//g;
$string =~ s/\s+$//g;
$string =~ s/\\/\\\\/g;
$string =~ s/\'/\\\'/g;
$string =~ s/\%/\\\%/g;
$string =~ s/[^\w\s\~\`\!\@\#\$\%\^\&\*\(\)\+\-\=\[\]\\\{\}\|\;\'\"\:\,\.\/\?\<\>]//g;
return $string;
}
No comments:
Post a Comment