Can I sanatise user input like this?

Bes

Bes

Soldato
Joined
18 Oct 2002
Posts
7,318
Location
Melbourne
Hi,

I am using javascript to set a load of data client- side in some hidden text fields, which is then posted to PHP. I am trying to sanatise the input when it hits PHP using a ternary operator, but I cannot get this working.... In this example, if leftFSVal is not a double digit int, I go to the default value of 20 and continue processing.

PHP:
 $_POST['leftFsVal'] = ("/\d\d/") ? $_POST['leftFsVal'] : $_POST['leftFsVal']=20;

A) Is this a valid way to do it?
B) If so, what am I doing wrong?

Thanks
 
Erm, you need to put some kind of regex function call in there, otherwise it's just evaluating the truth of the string "/\d\d/".

PHP:
$_POST['leftFsVal'] = preg_match("/\d\d/", $_POST['leftFsVal']) ? $_POST['leftFsVal'] : $_POST['leftFsVal']=20;

Regular expressions aren't first-class language constructs in PHP like they are in Perl :)
 
A slight modification, you can use PHP's built in min() and max() functions to force miniumum and maximum values for the input. The example below ensure that that the input is a double digit and also that the input value is 15 or greater. You can combine both min and max to set bounds, just an extra bit of checking if you want to constrain the 10-99 range even futher.

PHP:
$_POST['leftFsVal'] = preg_match("/\d\d/", $_POST['leftFsVal']) ? max($_POST['leftFsVal'], 15) : $_POST['leftFsVal']=20;

For example, to limit the number to 15 - 75 you would use:

PHP:
min(max($num, 15), 75)
 
Last edited:
Back
Top Bottom