keep textarea input format after using mysql_real_escape_string to store

前端 未结 5 995
时光说笑
时光说笑 2021-01-14 05:05

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?

相关标签:
5条回答
  • 2021-01-14 05:49

    The Best Solution..

    $insertdata = mysql_real_escape_string($string); (You can insert it in your database if you want)

    echo stripslashes(str_replace('\r\n',PHP_EOL,$insertdata)); (The output is exactly as your input was)

    0 讨论(0)
  • 2021-01-14 05:50

    You must escape data before inserting it into the database, to ensure you do not produce broken queries and to avoid SQL injections. However, when you retrieve that data via a SELECT, you'll receive the data unescaped, ready to be used.

    0 讨论(0)
  • 2021-01-14 05:51

    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.

    0 讨论(0)
  • 2021-01-14 06:05

    Short answer:

    // double quotes are *very* important, or chars are not interpreted
    $text_from_db=str_replace("\\r","\r",str_replace("\\n","\n",$text_from_db));
    

    Long answer

    Pretty simple but tricky. You write your textarea and hit the "return" key, there is placed a \r\n (on Windows systems) with slashes that escape the "r" and "n" letter rising their special meaning of carriage return and newline. You actually can't see them because they are "not printable" chars. The slash char itself (0x1B) is invisible, that is a single slash is a "not printable" char, to make it visible you have to "transform" it in a printable slash char (0x5C) and to achieve that you have to double it "\\". Now back to the question: if you can read the slash, probably that's beacuse that slash is not the 0x1B but rather 0x5C, so the "n" and "r" lose their special meaning and you get them as mere strings. The code I posted does this conversion, converting the "[0x5C]n" string in a "[0x1B]" char.

    Notes

    Hope this helps, it did for me. IMPORTANT : it is not normal that the text that comes from the db has this issue if it has been stored correctly. My suggestion is to triple check insertion and retrieving because (given from the issue) you could be applying the quoting twice somewhere.

    0 讨论(0)
  • 2021-01-14 06:06

    MySQL escapes the string, but when displaying the result back to you it will give you the same result as if it was unescaped.

    0 讨论(0)
提交回复
热议问题