I was wondering which code is more effective, meaning faster & reliable. When I have my client post data into my website, I don't allow them to use anything else other than Alphanumeric characters because there's no need for others. My question was, would an exception be faster and more reliable for this? Or should I stay away from exceptions in this purpose? Here's my code.
Normal Way -
function checkStr ($str)
{
if (preg_match('/[^0-9a-zA-Z]/', $str) > 0))
{
return false;
}
else
{
return true;
}
}
if (checkStr($_POST['field']) == true)
{
//continue
}
else
{
echo "Invalid characters";
}
Exception -
function checkStr ($str)
{
if (preg_match('/[^0-9a-zA-Z]/', $str) > 0)
{
throw new Exception('Invalid characters');
}
return true;
}
try
{
checkStr($_POST['field']);
//no exception, continue with code
}
catch (Exception $e)
{
echo $e->getMessage();
}
}