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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much @Brad. The htmlspecialchars will transform some special characters like & (ampersand) becomes &amp; " (double quote) becomes &quot; ' (single quote) becomes &#039; < (less than) becomes &lt; > (greater than) becomes &gt; in html. With that, the javascript execution will be avoid, right?
@Ana, That is correct, unless you were to wrap that output in <script> tags. The concept is that without <script> tags, the JavaScript can't execute. It just appears as text on the page. There is no way for someone to insert <script> tags, as they would turn out to be &lt;script&gt;.
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.
I am here again. The solution is perfectly adapted to my needs. Thank you.
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.

1 Comment

Of course, but the link is much appreciated. Not sure how I've missed this over the years...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.