I am using comment system like this:(i have simplified code for this question)
<?php
$status_ui = '<textarea id="box"></textarea>';
$status_ui .= '<button id="status_button" onclick="postComment(\'box\')">Post</button>';
?>
<html>
<head>
<script type="text/javascript">
function postComment(box){
var data = document.getElementById(box).value;
data = data.replace(/[^a-zA-Z0-9,.?! ;:'"]+/, '');
var hr = new XMLHttpRequest();
hr.open("POST", "comment_system.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var html_output = "";
current_html = document.getElementById("comment_list").innerHTML;
html_output += '<div class="comment">';
html_output += data;
html_output += '</div>';
document.getElementById("comment_list").innerHTML = html_output + current_html;
}
results_box.innerHTML = html_output;
}
}
hr.send("comment="+data);
</script>
</head>
<body>
<div id="container">
<?php echo $status_ui; ?>
<div id="comment_list"></div>
</div>
</body>
</html>
Users can enter only a-zA-Z0-9,.?! ;:'" and everything works super cool.
In comment_system.php, I am performing all kinds of checks, regex, in order to store my data safely to DB. The question is: how to output the user comment securely to the comment_list div to be XSS proof?
I am using string.replace,and I am aware that it can be bypassed by the bad user.