Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 333
Jonathan Rioux Avatar asked Mar 03 '26 04:03

Jonathan Rioux


2 Answers

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.

like image 113
Joe Avatar answered Mar 05 '26 16:03

Joe


If you mean you simply want to make it safe to store in your database all you need to do is use the database specific escaping method, for example mysql_real_escape_string. Of course, that doesn't secure you from XSS attacks, but if you want to retrieve and display it unmodified you don't have a choice.

like image 33
Hamish Avatar answered Mar 05 '26 16:03

Hamish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!