简体   繁体   中英

php htmlspecialchars

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?

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 &quot; , &lt; , &amp; , etc.

You should not be using htmlspecialchars on database data. Escape the text when you output it, not when you store it.

I will use htmlentities() most of the time.

You usually apply them to data when you're displaying the data.

Eg

you have $str = '<iframe src="http://someurl..." />';

If you use htmlentities when outputting, the < and > are converted into html entity - &lt; and &gt;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM