当前位置: 动力学知识库 > 问答 > 编程问答 >

php - encoding/decoding textarea value using rawurlencode/rawurldecode

问题描述:

When encoding newline of textarea before storing into mysql using PHP with rawurlencode function encodes newline as %0D%0A.

For Example:

textarea text entered by user:

a

b

encoding using rawurlencode and store into database will store value as a%0D%0Ab

When retrieving from database and decoding using rawurldecode does not work and code gives error. How to overcome this situation and what is the best way to store and retrieve and display textarea values.

网友答案:

can you first encode this textarea string using base64_encode and then perform a base64_decode on the same, if the above does not work for you.

If the textarea does not contain URLs, you should rather use base64_encode then rawurlencode and then store as normal.

网友答案:

You simply should not use rawurlencode for escaping data for your database.

Each target format has it's own escaping method which in general terms makes sure it is stored/display/transferred safely from one place to another, and it doesn't need decoding at the other end.

For instance:

  • displaying text in HTML, use htmlentities or htmlspecialchars
  • storing in database, use mysqli_real_escape_string, pg_escape_string, etc...
  • transferring variablename, use urlencode
  • transferring variablecontent, use rawurlencode
  • etc...

You should notice that decoding these things is often done by the browser/database. So no data is actually stored escaped. And decoding doesn't need te be done by your code.

The problem is probably because you escape a sequence with rawurlencode, but your database expected the escaped format for the specific brand of database. And de-escaped it using that assumption, which was wrong, which messed up your string.

Conclusion: find out what brand database you are using, look up the specific escape function for that database, and use the proper escaping function on all your content "transferral".


P.S.: some definition may not be correct, please comment on that. I wanted to make the idea stick but am probably not using all the right terms.

网友答案:

First of all it is very uncommon to run textarea through urlencode() urlencode was not designed for this purpose.

Second, if you still want to do this, then maybe the problem comes from database. First you need to tell us what database you using and what TYPE you using for storing this data: do you store it as TEXT or as BINARY data? Have you setup the correct charset in database?

分享给朋友:
您可能感兴趣的文章:
随机阅读: