I need to be able to safely display user inputted text in the DOM and I'm currently using the following JS to do that (it limits what characters are accepted).
But, now I'd like to allow all characters. How can I accept all characters, but encode them so that the user cannot execute a script or do anything bad.
function displayUserInput() {
var status = $('#text_input').val();
status = stripName(status);
$.ajax({ type: 'POST', url: "api.php?status="+escape(status), success: function(data){
// success
}});
}
function stripName(name) {
var new_name = new String(name);
new_name = new_name.replace(/[^a-zA-Z0-9:\(\/\)\s\.,!~-]/g, '');
return new_name;
}
On the PHP side I use the following code before saving the the user inputted text to the database:
$status_message = $_REQUEST['status'];
$status_message = preg_replace("/[^a-zA-Z0-9:\(\/\)\s\.,!~-]/", "", $status_message);
$status_message = mysql_real_escape_string($status_message);
It seems that my current method sanitizes the input fine, but I'd like to accept the full character set. Also, I am seeing some issues, for instance one user inputted text block is being displayed as:
u0627u0644u0644u0647 u0627u0643u0628u0631u0645u0646 u0627u0645u0631u064Au0643u0627
I'm assuming something went wrong in the encoding / decoding process...