开发者

Escaping single quote in PHP

I have an admin page which handles adding of product. I used mysql_real_escape_string on protecting my database from unnecessary characters. But when I get these data from the database (e.g. product name with single quote like Dave's Box), I had a error when displaying it on my page in the onclick attribute.

I used t开发者_开发百科his code for displaying the product code.

echo "<li onClick='fill(\"$productName\")'><strong>".stripslashes($row['name'])."</strong> by ".stripslashes($row['brand'])."</li>";


You should protect your code from quotes, dbl-quotes and HTML tags. To do that use PHP's htmlspecialchars() with ENT_QUOTES set. Example:

 htmlspecialchars($row['name'], ENT_QUOTES);


Use json_encode for the product name in the javascript function call, and htmlspecialchars for the normal HTML output.


To subsume the other answers:

  • use json_encode to encode the $productName value properly as JavaScript string and
  • use htmlspecialchars with the quote style ENT_QUOTES to encode it properly to be used in a single quotes HTML attribute value.

So:

echo "<li onClick='" . htmlspecialchars('fill('.json_encode($productName).')', ENT_QUOTES) . "'><strong>" . htmlspecialchars(stripslashes($row['name'])) . "</strong> by " . htmlspecialchars(stripslashes($row['brand'])) . "</li>";


You need to use addslashes() and possibly htmlentities() depending on the type of valid product names you allow.

http://php.net/manual/en/function.addslashes.php

http://php.net/manual/en/function.htmlentities.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜