I am posting the contents of a form field to a PHP script via AJAX and using JavaScript to escape (field_contents). The problem is that any plus signs are removed and replaced with spaces. How can I safely "encode" the plus sign and then "decode" it appropriately in PHP?
P粉0109671362023-07-22 00:53:41
Try it in JavaScript:
encodeURIComponent()
PHP:
urldecode($_POST['field']);
P粉6749994202023-07-22 00:39:11
Use encodeuriccomponent() in JS and PHP and you should receive the correct value.
Note: When you access $_GET, $_POST, or $_REQUEST in PHP, you are retrieving an already decoded value.
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']; // "+"
Only the original HTTP request contains URL-encoded data.
For GET requests, you can retrieve it from the URI. $_SERVER['REQUEST_URI'] or $_SERVER['QUERY_STRING']. For urlencoded POST, file_get_contents('php://stdin')
Note:
Decode() only applies to single-byte encoded characters. It doesn't work for the entire UTF-8 range.
eg:
text = "\u0100"; // Ā // incorrect escape(text); // %u0100 // correct encodeURIComponent(text); // "%C4%80"
Note: "Ā"
is equivalent to: escape('\xc4\x80')
This is the byte sequence representing Ā in UTF-8 (\xc4\x80). So if you use encodeuriccomponent(), your server side must know that it is receiving UTF-8. Otherwise PHP will mess up the encoding.