你应该在isset()和empty()之前或之后使用htmlspecialchars()吗?

I was wondering what is the correct procedure when it comes to security and practicality. Should you use htmlspecialchars() on a variable before you check if it's set and empty?

Examples:

Use htmlspecialchars() on use or storage of post data:

$field = $_POST['field'];
if(isset($field)){
    //store or use: htmlspecialchars($field);
}

Or should you use htmlspecialchars() on retrieval of the post data:

$field = htmlspecialchars($_POST['field']);
if(isset($field)){
    //store or use: $field
}

This is probably a silly question, but I wanted to know which is correct.

Well, think about it this way. Why do we use isset in the first place? The answer is to protect our code from trying to do things with something that doesn't exist.

For example, using php -a in your console, you can see:

php > $temp
php > echo htmlspecialchars($temp);

Parse error: parse error in php shell code on line 2
php >

Clearly you don't want your code throwing parse errors. So, you need to check that the value exists first (using isset), then do things with that value.

You should use both isset and empty if you want to make your condition fully secure, Because isset checks that variable is defined or not and empty checks for the value of variable is empty or not. So you should use your if condition like this,

$field = $_POST['field'];
if(isset($field) && !empty($field)){
    //store or use: htmlspecialchars($field);
}