清理前的用户输入验证?

If I want to validate user input, is it necessary to sanitize it beforehand?

$age = $_POST['age'];
if ($age == 18) {
    echo 'is 18';
}
else
{
    echo 'Is not 18';
}

does this example leave me vulnerable to attack? Should I have sanitised age before the if/else block?

$age = htmlentities($_POST['age'])

or

$age = stripslashes($_POST['age'])

There is no possibility of any attack here. The input string is not evaluated as code or otherwise attempted to be executed in any way. You're just comparing a string to another string/number, which is a safe operation.