<a href="

时间:2015-05-01 16:45:44

标签: php mysql html-entities

="" My MySQL database has some fields that sometimes include an apostrophe, so I take care to encode html entities. For example "Cote d'Or" is stored in the database as "Cote d&039;Or".

When a MySQL query populates an href I get something like this in my source code.

<a href="/page.php?location=Cote d&039;Or">Text link</a>

However when I click on the link I get a 403 "Forbidden" error. On checking, hovering on the link says it is reading &039; as an apostrophe. That seems to be the cause of the page error as putting an apostrophe in the database produces the same error and having nothing in there works correctly.

My question now is, how can I have the html entity in the database and still get the link to work correctly?

3 个答案:

答案 0 :(得分:2)

对于网址,您不希望使用htmlentities()作为显示HTML的内容。

相反,您需要使用urlencode()

$link = '/page.php?location=' . urlencode($location);

如果您的数据已经过HTML编码,则需要在传递urlencode()之前对其进行解码。一个很好的功能是html_entity_decode()

$location = html_entity_decode($row['location']);
$link = '/page.php?location=' . urlencode($location);

答案 1 :(得分:0)

您最好使用filter_var($var, FILTER_SANITIZE_URL)

答案 2 :(得分:0)

虽然不是最佳方法,但由于您使用的是htmlentities(),因此您可以使用html_entity_decode()

来自:http://php.net/html_entity_decode

  

html_entity_decode()与htmlentities()相反,它将字符串中的所有HTML实体转换为适用的字符。

相关问题