This may be obvious to most experienced developers,but just in case its not,when using preg_grep to check for whitelisted items ,one must be very careful to explicitly define the regex boundaries or it will fail
$whitelist= ["home","dashboard","profile","group"];$possibleUserInputs= ["homd","hom","ashboard","settings","group"];
foreach($possibleUserInputsas$input)
{
if(preg_grep("/$input/i",$whitelist)
{
echo$input." whitelisted";
}else{
echo$input." flawed";
}
}?>This results in:
homd flawed
hom whitelisted
ashboard whitelisted
settings flawed
group whitelisted
I think this is because if boundaries are not explicitly defined,preg_grep looks for any instance of the substring in the whole array and returns true if found.This is not what we want,so boundaries must be defined.
{
if(preg_grep("/^$input$/i",$whitelist)
{
echo$input." whitelisted";
}else{
echo$input." flawed";
}
}