Php – keep textarea input format after using thesql_real_escape_string to store

escapingMySQLPHPtextarea

I am using php5.3.6 and mysql 5.1.56 and CodeIgniter. Here is what I did.

  1. Input some text in textarea, something like this:


    what's this?

    I'm bob.


  2. $string = $_POST['name'];

  3. $insertdata = mysql_real_escape_string($string);

  4. Insert $insertdata into database.
    It shows "what\'s this?\n\n\nI\'m bob."(without double quotes) in the table.

  5. Query the data stored in database, use stripslashes on it and then put it back to the textarea.
    It shows "what's this?nnnI'm bob."(without double quotes) in the textarea.

My questions are:

  • In step 4, shouldn't it be "what\'s this?\n\n\n I\'m bob." stored in the table?
    I checked php manual. It says:

mysql_real_escape_string() calls
MySQL's library function
mysql_real_escape_string, which
prepends backslashes to the following
characters: \x00, \n, \r, \, ', " and
\x1a.

  • How am I supposed to keep the textarea input format after using mysql_real_escape_string()?

  • Is there anyway to choose which slash to strip and which not to?

Notes:

  • magic quotes option is off
  • I did not use stripslashes() before
    using mysql_real_escape_string()
  • If I use addslashes() instead of
    mysql_real_escape_string(),
    everything works fine.
  • I don' want to use addslashes() since
    it is not as secure as
    mysql_real_escape_string(), as far as
    I know.

Thanks,
Milo

Best Answer

This really does feel a lot like magic_quotes_gpc = On. Are you disabling it in php.ini or at runtime? It needs to be the former, otherwise it'll remain on.

http://www.php.net/manual/en/security.magicquotes.disabling.php

The magic_quotes_gpc directive may only be disabled at the system level, and not at runtime. In otherwords, use of ini_set() is not an option.