views:

27

answers:

1

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...

+2  A: 

To make data safe for displaying on a page, you only need to escape < and > and replace them with &lt; and &gt; respectively. And the MySQL escape as usual when saving to the database. I don't understand why you need all the regular expressions like you have now.

casablanca
Ok, good point. That solves the sanitization problem. Any idea why special characters such as ★ would be displayed as %u2605. I imagine I could decode in PHP before displaying, but I'm worried this would allow users to sneak in < and >
makeee
That's probably because the browser encodes POST data before sending it to the server. You should decode it in PHP, *then* escape `<` and `>` and finally do a MySQL escape and store it in the DB. When retrieving, you simply need to display the text.
casablanca