Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing <script> tag - PHP

Tags:

javascript

php

How to change all the occurrence of the <script> <Script> <scRipT> <sCrIpT> and so .. to &lt;script&gt; &lt;Script&gt; with PHP
I also want to remove

The input will be taken from a WYSIWYG Editor, so i can not use the strip_tags function.

Edit 2
Is there any other way a user can execute a javascript with some kind of strange characters to
I found this on internet

<scr<!--*-->ipt>
alert('hi')
</script>

But it did not worked though, is there any such possibilities ?

like image 812
Sourav Avatar asked May 13 '11 02:05

Sourav


2 Answers

Simply removing <script> tags from untrusted input is not enough to guard against XSS attacks. For example, <a href="#" onmouseover="alert('pwned!');"> – I just put script in your page—without using a <script> tag—and stole your cookies. Oops.

This is a case where you really need to use a well-tested library that actually parses the HTML and removes the stuff you don't want.

like image 93
josh3736 Avatar answered Sep 30 '22 15:09

josh3736


Probably the simplest method would be str_ireplace() for case-insensitive replacement, however this won't preserve the case of the "sCriPt" word. But if you're out to de-fang XSS attacks that may be just fine:

str_ireplace("<script>", "&lt;script&gt;", $input);

A more complex solution could be devised with preg_replace() to preserve case, but would be slower. This might work, but if it were me I'd use str_ireplace()...

preg_replace("/<(script)>/i", "&lt;$1&gt;", $input);

Note: If it is XSS prevention you're after, neither of these takes into account things like <script type=text/javascript>. To truly handle these cases, you need to load the HTML string into DOMDocument and delete the offending script nodes.

like image 37
Michael Berkowski Avatar answered Sep 30 '22 13:09

Michael Berkowski