Use preg_match to see if a line contains script -tags

How do I write a template to use with PHP's preg_match function to check if a string containing script-tags contains?

+2


source to share


3 answers


Are you trying to avoid them? if yes try the following (not tested)

$string=str_replace(array("&", "<", ">"), array("&amp;", "&lt;", "&gt;"), $string);

      



Thus, a surprise awaits your attackers.

0


source


For security reasons? Basically, you can't. Here are some of the things I've learned in the past:

  • <a href="javascript:something">...</a>

  • <p onmouseover="something">

  • There are several URL schemes that are equivalent in different browsers javascript:

    , such jscript:

    as mocha:

    and livescript:

    . Most of them are undocumented.
  • Older versions of Netscape treated certain bytes (0x94 and 0x95, I guess?) As equivalent <>

    . I hope there is nothing like this in modern browsers.
  • VBScript.


MySpace tried to do this, and the result was the Sammi My Hero worm, which took the service off within a day or so, among many other security disasters on their part.

So, if you want to accept a limited subset of HTML that only includes text and formatting, you should have a whitelist, not a blacklist. You have a whitelist of tags, attributes and if you want to allow links, URL schemes. There are several existing libraries for this, but I don't know which ones are recommended in PHP.

+3


source


Don't use regular expressions for xml / html processing. You are better off using the PHP classes DOM , it should be much more reliable than any regex you find:

$document = new DOMDocument();
$document->loadHtml($html);
$xpath = new DOMXPath($document);
if ($xpath->query('//script')->length > 0) {
    // document contains script tags
}

      

+1


source







All Articles