phpmysqlapachetextareasanitize

PHP - Non-destructive Input Sanitization


I have a TextArea on my website which I write the input into my database.

I want to filter this TextArea input, but without removing any HTML tags or other stuff.

In short, I want to sanetize and securize the input before I write it into my database, but I want the entry to be intact and unmodified when I take back the entry from the database and write it on the website.

How can I achieve this?


Solution

  • If you want to preserve the data character for character when it's written back to the website try:

    $stringToSave = mysql_real_escape_string($inputString);
    

    Then when retrieving it from the database:

    $stringToPutOnPage = htmlentities($databaseString);
    

    If you want the html to actually be read as html (be careful about XSS) you can just use:

    $stringToSave = mysql_real_escape_string($inputString);
    

    Edit: It would seem that best practice is to sanitize the string for html after retrieving it from the database and not before. Thanks for the comments, I will have to change my method.