What is the best way to prevent XSS?

advertisements

Which is better method to prevent XSS attacks? Here is the code I am trying to do.

Is this line of code enough to prevent XSS attacks? or Do I have to parse each element with 'strip_tags'. Thank you for any suggestions.

  $xss = array_map('strip_tags', $_POST);

OR

In this method I have to change a lot of form elements with 'strip_tags'.

$f_name = strip_tags($_POST["f-name"]);
$a_id = isset($_POST['a_id']) ? (int)strip_tags($secure_POST['a_id']) : 0;

$qry = $pdo_conn->prepare('INSERT INTO TABLE1(id, f_name) VALUES (?, ?)');
$qry->execute(array($a_id, $f_name));


XSS means Cross Site Scripting and is injecting a website with malicious html elements. This can be prevented by setting a proper charset (like utf8) and htmlentities when displaying it.

You want to keep original data in your database, just in case. If you would ever change anti-XSS tactics you can do that all at once, because the data is not already prepared.

I think you mean anti sql-injection. Prepared statements do that themselfs (if defined proper charset like utf8), no need to worry about that. You can do some checks beforehand though, like checking if $_POST['int'] really only has int values (as example).