Store html entities in database? Or convert when retrieved?

后端 未结 8 1213
自闭症患者
自闭症患者 2020-12-03 01:13

Quick question, is it a better idea to call htmlentities() (or htmlspecialchars()) before or after inserting data into the database?

8条回答
  •  失恋的感觉
    2020-12-03 01:44

    In a php/MySQL web app, data flows in two ways

    Database -> scripting language (php) -> HTML output -> browser ->screen and Keyboard-> browser-> $_POST -> php -> SQL statement -> database.

    Data is defined as everything provided by the user.

    ALWAYS ALWAYS ALWAYS....

    A) process data through mysql_real_escape_string as you move it into an SQL statement, and

    B) process data through htmlspecialchars as you move it into the HTML output.

    This will protect you from sql injection attacks, and enable html characters and entities to display properly (unless you manage to forget one place, and then you have opened up a security hole).

    Did I mention that this has to be done for every single piece of data any user could ever have touched, altered or provided via a script?

    p.s. For performance reasons, use UTF-8 encoding everywhere.

提交回复
热议问题