php - Function to check GET parameter -
i have function security check on parameter (i'm not author):
function get($name = null, $value = false) { $content = (!empty($_get[$name]) ? trim($_get[$name]) : (!empty($value) && !is_array($value) ? trim($value) : false)); if (is_numeric($content)) return preg_replace("@([^0-9])@ui", "", $content); else if (is_bool($content)) return ($content ? true : false); else if (is_float($content)) return preg_replace('@([^0-9\,\.\+\-])@ui', "", $content); else if (is_string($content)) { if (filter_var($content, filter_validate_url)) return $content; else if (filter_var($content, filter_validate_email)) return $content; else if (filter_var($content, filter_validate_ip)) return $content; else if (filter_var($content, filter_validate_float)) return $content; else return preg_replace('@([^a-za-z0-9\+\-\_\*\@\$\!\;\.\?\#\:\=\%\/\ ]+)@ui', "", $content); } else false; }
so whenever i'm fetching parameter values call function. however, if parameter string containing special characters åäö
replaced. example, string detta är en annons
have following output: detta r en annons
.
since i'm sure it's string variable it's filter_var
function strips special chars. how should rewrite above script keep special characters in string?
edit
okay, above script thrash. i've been looking @ alternatives. if purpose insert parameter value database, filter_input(input_get,"link",filter_sanitize_string);
sufficient clean variable malicious code?
strictly answering question, problem lay in preg_replace
. in original version, characters other ones explicitly listed replaced "", removing them input. example, "2^8" become "28", because ^
not allowed.
to accept character other "invisible control characters , unused code points", replace preg_replace
in function this:
return preg_replace('@(\p{c})@ui', "", $content);
edit
responding op edit, filter_input
great way remove potentially dangerous input , may want in specific use case. however, please understand there isn't magic bullet solution. have @ this related q&a.
at rate, typically want check user input conforms storage requirements (type, length, etc), use prepared statements insert database, use output escaping prevent xss attacks. pseudo-code goes this:
$foo = isset($_get['foo') ?? false; if (is_string($foo) && 0 < strlen($foo) && strlen($foo) < 255) { $sth = $dbh->prepare('insert `table` values (?)'); $sth->execute(array($foo)); echo htmlentities($foo); } else { echo 'error: foo not valid'; }
Comments
Post a Comment