2

I have some variables in PHP (strings) and I vould like to check if inside of those strings I have some javascript code. If so, I would like to make this code inactive and be displayed as string on the website, not to be executed as javascript code.

This will be a kind of security method.

Is there a method to do it in php? If you could give me an example, it's even better.

Thank you very much for your help.

Charles
  • 50,943
  • 13
  • 104
  • 142
Milos Cuculovic
  • 19,631
  • 51
  • 159
  • 265

2 Answers2

7

You should be using htmlspecialchars() for any content you output into HTML. It escapes any HTML entities so that they are not taken literally. For example, < becomes &lt;. This also solves your problem.

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

Brad
  • 159,648
  • 54
  • 349
  • 530
  • Thank you very much @Brad. The htmlspecialchars will transform some special characters like & (ampersand) becomes & " (double quote) becomes " ' (single quote) becomes ' < (less than) becomes < > (greater than) becomes > in html. With that, the javascript execution will be avoid, right? – Milos Cuculovic Jul 24 '12 at 12:37
  • @Ana, That is correct, unless you were to wrap that output in ` – Brad Jul 24 '12 at 12:38
  • Great, thank you very much. I will take a couple of minutes to checki if this solution is properly adapted to my code and I will let you know as soon as possible. – Milos Cuculovic Jul 24 '12 at 12:39
  • I am here again. The solution is perfectly adapted to my needs. Thank you. – Milos Cuculovic Jul 24 '12 at 12:44
2

In addition to Brad's answer, consider reading the first answer here for a short summary and then the therein mentioned article afterwards.

This can help you to easily avoid outputting unsafe strings by accident.

Community
  • 1
  • 1
phant0m
  • 16,595
  • 5
  • 50
  • 82
  • Of course, but the link is much appreciated. Not sure how I've missed this over the years... – Brad Jul 24 '12 at 13:01