且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP& mySQL:何时确切使用htmlentities?

更新时间:2023-01-29 20:12:20

这是一般的经验法则.

最后可能的时刻转义变量.

您希望变量是数据的干净表示.也就是说,如果您要存储名为"O'Brien"的人的姓氏,那么您肯定想要这些:

You want your variables to be clean representations of the data. That is, if you are trying to store the last name of someone named "O'Brien", then you definitely don't want these:

O'Brien
O\'Brien

..因为,好吧,这不是他的名字:里面没有&"号或"/"号.当您使用该变量并将其输出到特定的上下文中(例如:插入SQL查询或打印到HTML页面)时,那个就是您对其进行修改的时候.

.. because, well, that's not his name: there's no ampersands or slashes in it. When you take that variable and output it in a particular context (eg: insert into an SQL query, or print to a HTML page), that is when you modify it.

$name = "O'Brien";

$sql = "SELECT * FROM people "
     . "WHERE lastname = '" . mysql_real_escape_string($name) . "'";

$html = "<div>Last Name: " . htmlentities($name, ENT_QUOTES) . "</div>";

您永远不想在数据库中存储htmlentities编码的字符串.如果要生成CSV或PDF或不是 HTML的任何内容,会发生什么?

You never want to have htmlentities-encoded strings stored in your database. What happens when you want to generate a CSV or PDF, or anything which isn't HTML?

保持数据整洁,仅在当前特定情况下转义.

Keep the data clean, and only escape for the specific context of the moment.