views:

1160

answers:

5

I have a textbox on my website and I need to store whatever the user enters into my database, and retrieve it at a later time. I need to store it exactly as the user entered, including special characters, carriage returns, etc.

What process should I use in PHP to store this in my database field (which is a 'text' field)? Should I use PHP's html_encode or anything like that?

Thankyou.

Edit: I also need to store correct formatting i.e tabs and multiple spaces.

+1  A: 

You don't have to encode it in order to store it in a mysql.

Be sure you use a parameterized insert command, to avoid SQL injection.

Assaf Lavie
+2  A: 

The following should work:

if (get_magic_quotes_gpc()) {
  $content = stripslashes($content);
}
$content = mysql_real_escape_string($content);

If your column is utf8, you shouldn't have problems with special characters. Once you've formatted the content correctly, you can feed it to mysql using your standard insert methods.

Jeremy Stanley
+3  A: 

Use mysql_real_escape_string():

$safetext = mysql_real_escape_string($_POST['text']);
$query = "INSERT INTO my_table (`my_field`) VALUES ('$safetext')";
mysql_query($query);

That should work.

Calvin
+2  A: 

You shouldn't html-encode the data when writing it to the datastorage - that way you could use your data also for something else (e.g. emails, PDF documents and so on). As Assaf already said: it's mandatory to avoid SQL injections by escaping the input or using parameterized insert-queries.

You should, no, let's say, must however html-encode your data when showing it on an HTML page! That will render dangerous HTML or Javascript code useless as the HTML-tags present in the data will not be recognized as HTML-tags by the browser any more.

The process is a little more complicated when you'll allow the users to post data with HTML-tags inside. You then have to skip the output-encoding in favor of an input-sanitizing which can be arbitrary complex depending on your needs (allowed tags e.g.).

Stefan Gehrig
A: 

to correctly store the user text in addition to the formatting, all you have to do is us the convert all the newlines to breaks using nl2br($inputtext). do this after filtering the input.

Simi King