0

I have a hidden field that stores value retrieved from the database as given below:

echo '<input type="hidden" value="'.$str.'">';

The problem is that if $str contains text having double quotes, it definitely causes problem for the browser to display accordingly. But using escape character \ in PHP is in vain. Also I tried this:

$str = str_replace('"',"'",$str);

Then I have to replace every single quotes into double (doing the reverse) in the client:

str = str.replace(/'/g,'"');

Although it works fine for me,still it doesn't get rid of bugs. For example, if the original string from the database contains single quote (') , it will also get replaced by double quote (") in the client which is unexpected. So, is there any alternative solution to this problem or is there really any escape character for browsers that can be put in the double quotes in the hidden field?

Parveez Ahmed
  • 1,325
  • 4
  • 17
  • 28
  • 1
    `"` becomes `"`. `htmlspecialchars()` – Brad Jul 02 '14 at 04:25
  • so what should I do now @Brad – Parveez Ahmed Jul 02 '14 at 04:27
  • http://stackoverflow.com/a/46491/362536 – Brad Jul 02 '14 at 04:33
  • thank you brad ... i already got it ... thanks again!! – Parveez Ahmed Jul 02 '14 at 04:34
  • 1
    You could also [`base64_encode()`](http://php.net/base64_encode) it. It has the same drawback of HTML-encoding stuff, in that you will probably have to decode it again at some point, but it should work well. – Sverri M. Olsen Jul 02 '14 at 04:39
  • @SverriM.Olsen Base64 encoding is built for making binary data safe for use as text. There is 33% overhead in size, not to mention encoding/decoding processing speed. Suggesting base64 as an alternative to proper escaping for HTML is probably one of the most ridiculous things I have ever heard. – Brad Jul 03 '14 at 05:09
  • @Brad I would agree that it is unconventional, but the *most ridiculous thing* ever... that is blowing it out of proportions. If you understand and do not mind the drawbacks then base64 encoding is a perfectly fine alternative to HTML encoding. The overhead you are talking about also applies to encoding; I would venture to say that they are roughly comparable. Even if base 64 encoding is 100 times slower than HTML encoding you would have to go through a performance benchmark with a toothpick to find it. – Sverri M. Olsen Jul 03 '14 at 06:58

1 Answers1

1

You can use htmlentities to escape the value

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

e.g.

echo '<input type="hidden" value="'.htmlentities($str).'">';

NoGray
  • 1,149
  • 7
  • 9