2

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.

KaveElite
  • 94
  • 9

2 Answers2

5

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.

Matthew Herbst
  • 29,477
  • 23
  • 85
  • 128
  • Okay, I understand. I was told to always use htmlspecialchars() when retrieving field information, wasn't sure if it was correct either way. I appreciate the clarification. – KaveElite Feb 17 '16 at 06:39
  • @KaveElite yes, always make sure to sanitize information you receive from "the outside". But first make sure you got something in the first place :D – Matthew Herbst Feb 17 '16 at 06:41
0

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);
}
Shivam
  • 702
  • 2
  • 10
  • 25