I have a basic form to submit comments to a database through PHP and display them on the page via AJAX, and everything works OK but the problem is that simple HTML code like <script>alert('Message')</script>
or <h1>Hi!</h1>
is displayed valid HTML and is executed by the client as such.
After doing research I've found that the PHP htmlspecialchars()
function can prevent XSS code from being executed:
<form method="post" action="<?PHP echo htmlspecialchars($_SERVER['PHP_SELF']);?>" onsubmit="return post();">
<textarea id="comment"></textarea>
<input type="submit" value="Submit">
</form>
the PHP document that processes the form is this:
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
$host="localhost";
$username="user";
$password="password";
$databasename="comments";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
if(isset($_POST['user_comm']))
{
$comment = mysql_real_escape_string($_POST['user_comm']);
$insert=mysql_query("insert into comments values('','$comment',CURRENT_TIMESTAMP)");
$id=mysql_insert_id();
$select=mysql_query("select comment,post_time from comments where comment='$comment' and id='$id'");
if($row=mysql_fetch_array($select))
{
$comment = mysql_real_escape_string($row['comment']);
$time=$row['post_time'];
?>
<div class="comment_div">
<p class="comment"><?php echo stripslashes($comment);?></p>
<p class="time"><?php echo date('l d M Y - H:i a', strtotime($time));?></p>
</div>
<?php
}
exit;
}
?>
But in my case that isn't working and Javascript code is still executed by the client after the message has been sent. How can I display HTML special characters as plain text on the comments to prevent that?