Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Sanitise a comma separated string

What would be the most efficient way to clean a user input that is a comma separated string made entirely on numbers - e.g

2,40,23,11,55

I use this function on a lot of my inputs

function clean($input){ $input=mysql_real_escape_string(htmlentities($input,ENT_QUOTES)); return $input; }

And on simple integers I do:

if (!filter_var($_POST['var'], FILTER_VALIDATE_INT)) {echo('error - bla bla'); exit;}

So should I explode it and then check every element of the array with the code above or maybe replace all occurrences of ',' with '' and then check the whole thing is a number? What do you guys think?

like image 402
Mark Avatar asked Feb 05 '26 06:02

Mark


1 Answers

if (ctype_digit(str_replace(",", "", $input))) {
  //all ok. very strict. input can only contain numbers and commas. not even spaces
} else {
  //not ok
}

If it is CSV and if there might be spaces around the digits or commas and maybe even some quotation marks better use a regex to check if it matches

like image 183
jitter Avatar answered Feb 07 '26 20:02

jitter