Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

php - Escaping variables

I've read that it's enough and even recommended to escape characters on the output, not on the input.

It could be easily applied to all get variables as they are not injected to the database from the form level.

However, I'm not sure what to do with all post variables. If it doesn't come from the database, so if it's a raw input data, escaping is fully needed. But I'm using PDO prepare/execute to escape all variables. Questions now:

  1. Is it OK to use PDO's prepare/execute both in select and insert statements? Isn't it escaping variables twice ?
  2. Let's say I get some variable through PDO exeute statement - is it ok to display this variable simply with $_POST['variable'] without escaping it (if it was already done in PDO function) ?
  3. Is htmlspecialchars() enough to escape things such as GET variables which don't come from the database?

And the most important - is all of this, PDO prepare/execute, and htmlspecialchars(), enough to prevent all XSS attacks? Or should I also do more? If so, what should this be? Removing all html tags from the input? Using BB-Code instead?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I've read that it's enough and even recommended to escape characters on the output, not on the input.

Typically, you want to:

  • Validate input and store it using prepared statements. Prepared statements will protect your database against SQL injections. Typically, you don't want to strip out HTML tags on input because doing so could lead to a loss of data integrity.
  • When displaying user-generated data (output), you can guard against XSS by using a combination of htmlentities and mb_convert_encoding.

Note on the htmlspecialchars function from another question:

Even if you use htmlspecialchars($string) outside of HTML tags, you are still vulnerable to multi-byte charset attack vectors.

The most effective you can be is to use the a combination of mb_convert_encoding and htmlentities as follows.

$str = mb_convert_encoding($str, ‘UTF-8′, ‘UTF-8′);
$str = htmlentities($str, ENT_QUOTES, ‘UTF-8′);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...