I have a form that users fill it and send their questions, and then administrator will answer them and finally these questions will be shown in website.
To prevent attacks, I've used PDO and htmlspecialchars() function. I don't apply any change on input data and only store them using PDO. But when I want to show them in the page, I use htmlspecialchars(). But this caused that even <p>
tags appear in the text as part of it. What is the problem and how can I solve it?
Storing questions:
$stmt = "INSERT INTO tbl_questions (title,question) VALUES (?,?)";
$q = $db->prepare($stmt);
$q->execute(array($_POST['title'],$_POST['question']));
Displaying questions:
echo htmlspecialchars($title).'<br />'.htmlspecialchars($question);
The method htmlspecialchars
is not perfect.
Take a look at htmlpurifier. It is way more powerfull through whitelist filter. With it, your users can write html (such as <p>
), and you don't have the risk of XSS.
consider, to use this, before you store it in the database, so you don't need to santize your input on every page view.