0

Like we use htmlspecialchars to avoid html tag as input.

Similarly, Is there any function or method that we can use to avoid javascript too.?

htmlspecialchars does not take care of script tag.

any suggestions. ?

Ameya
  • 63
  • 1
  • 10
  • 1
    you can use htmlentities().It prevents using all html tags – NavidIvanian Aug 27 '15 at 18:48
  • Also, please make sure to scrub the data on the server side as well, since attackers could submit data directly to the server and bypass the client-side protections. – raduation Aug 27 '15 at 18:49
  • 1
    possible duplicate of [The definitive guide to form-based website authentication](http://stackoverflow.com/questions/549/the-definitive-guide-to-form-based-website-authentication) – Script47 Aug 27 '15 at 18:54

2 Answers2

2

Use filter_input and the FILTER_SANITIZE_FULL_SPECIAL_CHARS flag.

This will convert < and > to &lt; and &gt;, respectively.

$input = filter_input(INPUT_POST, 'fieldName', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

So this:

<script>alert('hello');</script>

Becomes this:

&lt;script&gt;alert(&#039;hello&#039;);&lt;/script&gt;

Take a look at the different sanitize filters. Instead of using fullspecialchars on everything, use the filter that applies to the input you're expecting... ex. if you're asking for a number, use a number filter.

chris85
  • 23,255
  • 7
  • 28
  • 45
chrisjacob
  • 160
  • 12
  • I tried this: $str = ""; $str = filter_var($str, FILTER_SANITIZE_STRING); echo $str; Output: alert('Hello'); Thats Ok however is there anyway I can use it as TRUE or FALSE... ? if $str Contains html tags, it should exit and not enter details in DB. – Ameya Aug 27 '15 at 19:29
  • Thanks, I could achieve, what I wanted to. Thank you again. – Ameya Aug 27 '15 at 19:53
  • You could do something along the lines of `if($input != filter_var($input, ...)){ return false;}` – chrisjacob Aug 27 '15 at 19:57
0

It should take care of the script tags, as the < and > tags are translated.

< (less than) becomes &lt;

> (greater than) becomes &gt;

See the PHP documentation: http://php.net/manual/en/function.htmlspecialchars.php

chris85
  • 23,255
  • 7
  • 28
  • 45
P.Yntema
  • 528
  • 1
  • 6
  • 24