Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

security - PHP htmlentities() on input before DB insert, instead of on output

I wonder if there's any downside or bad practice in doing the following procedure:

  1. $user_input -> htmlentities($user_input) -> mysql_escape($user_input) -> insert $user_input into DB
  2. Select $user_input from DB -> echo $user_input

instead of doing the following:

  1. $user_input -> mysql_escape($user_input) -> insert $user_input into DB
  2. Select $user_input from DB -> echo htmlentities($user_input)

As we display the same $user_input on a lot of places it feels more efficient do to it on the input instead, are there any downsides / bad practice / exploit-ability in doing it this way?

Cheers!

Good replies to the question from:

@Matt: In general, to keep things readable and maintainable, try to store it as close to the original, unfiltered content as possible. It depends on two things: Is any other person/program going to reference this data? Does the data need to be easily editable?

@Sjoerd: There is a downside if you want to display the data as something else than HTML, e.g. a CSV download, PDF, etc.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

It depends on two things:

  • Is any other person/program going to reference this data?
  • Does the data need to be easily editable?

The advantage of method one is that, in the case that the data is used in one place, and htmlentities() would be called every time, you'd be saving this step.

However, this would only leave a notable improvement if the HTML data is very large. In general, to keep things readable and maintainable, try to store it as close to the original, unfiltered content as possible.

In fact, you might find that HTML is the wrong thing to store anyway. It might be better to store something like Markdown and simply convert it to HTML when viewed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...