Reputation: 8091
what type of input should I be using htmlspecialchars with? or should I always use it to sanitize input data? or are there any better 'data sanitizing' functions? That is assuming that these values will be stored in a database
Example:
$userdata = array(
'username' => $_POST['username'],
'email' => $_POST['email'],
'password' => $_POST['password']
);
// register function defined in a class user accepts array as parameter
// register function hashes password before storage
$this->user->register($userdata);
should i apply htmlspecialchars to these data?
Upvotes: 1
Views: 750
Reputation: 38740
htmlspecialchars should be used on any data a user enters that is ever displayed back to any of your users. If you don't use it for even 1 piece of information, you've opened yourself up to a Cross Site Scripting attack.
You wouldn't use it when adding information to a database or saving it somewhere, then you'd want to properly escape it for your database. This will avoid a SQL injection vulnerability.
Upvotes: 1
Reputation: 43619
I will use htmlentities()
most of the time.
You usually apply them to data when you're displaying the data.
E.g.
you have $str = '<iframe src="http://someurl..." />';
If you use htmlentities when outputting, the < and > are converted into html entity - < and >
Upvotes: 1
Reputation: 361565
As the name implies, htmlspecialchars
is intended to be called when you're outputting a string inside your HTML output. For example:
<input type="text" name="username" value="<?= htmlspecialchars($user->name) ?>" />
Calling it there ensures that quotes, angle brackets, and such are properly encoded with their corresponding entities "
, <
, &
, etc.
You should not be using htmlspecialchars
on database data. Escape the text when you output it, not when you store it.
Upvotes: 1