Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
120
rated 0 times [  127] [ 7]  / answers: 1 / hits: 143041  / 15 Years ago, thu, september 3, 2009, 12:00:00

I'm POSTing the contents of a form field via AJAX to a PHP script and using JavaScript to escape(field_contents). The problem is that any plus signs are being stripped out and replaced by spaces. How can I safely 'encode' the plus sign and then appropriately 'decode' it on the PHP side?


More From » ajax

 Answers
100

Use encodeURIComponent() in JS and in PHP you should receive the correct values.



Note: When you access $_GET, $_POST or $_REQUEST in PHP, you are retrieving values that have already been decoded.



Example:



In your JS:



// url encode your string
var string = encodeURIComponent('+'); // %2B
// send it to your server
window.location = 'http://example.com/?string='+string; // http://example.com/?string=%2B


On your server:



echo $_GET['string']; // +


It is only the raw HTTP request that contains the url encoded data.



For a GET request you can retrieve this from the URI. $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING']. For a urlencoded POST, file_get_contents('php://stdin')



NB:



decode() only works for single byte encoded characters. It will not work for the full UTF-8 range.



eg:



text = u0100; // Ā
// incorrect
escape(text); // %u0100
// correct
encodeURIComponent(text); // %C4%80


Note: %C4%80 is equivalent to: escape('xc4x80')



Which is the byte sequence (xc4x80) that represents Ā in UTF-8. So if you use encodeURIComponent() your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.


[#98764] Monday, August 31, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacied

Total Points: 124
Total Questions: 84
Total Answers: 98

Location: Ivory Coast
Member since Sun, Mar 7, 2021
3 Years ago
;