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?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- Carriage Return (ASCII chr 13) is missing from tex
- void before promise syntax
- Keeping track of variable instances
If you have to do a curl in php, you should use
urlencode()
from PHP but individually!If you do
urlencode(strPOST)
, you will bring you another problem, you will have one Item1 and & will be change %xx value and be as one value, see down here the return!Example 1
Example 2
Example 1 is the good way to prepare string for POST in curl
Example 2 show that the receptor will not see the equal and the ampersand to distinguish both value!
To make it more interesting and to hopefully enable less hair pulling for someone else. Using python, built dictionary for a device which we can use curl to configure.
Problem:
{"timezone":"+5"} //throws an error " 5"
Solution:
{"timezone":"%2B"+"5"} //Works
So, in a nutshell:
Thanks to this post!
my problem was with the accents (á É ñ ) and the plus sign (+) when i to try to save javascript "code examples" to mysql:
my solution (not the better way, but it works):
javascript:
function to save:
function in php:
The hexadecimal value you are looking for is
%2B
To get it automatically in PHP run your string through
urlencode($stringVal)
. And then run it rhoughurldecode($stringVal)
to get it back.If you want the JavaScript to handle it, useescape( str )
Edit
After @bobince's comment I did more reading and he is correct. Use
encodeURIComponent(str)
anddecodeURIComponent(str)
. Escape will not convert the characters, only escape them with\
'sUse
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:
On your server:
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:
Note:
"%C4%80"
is equivalent to:escape('\xc4\x80')
Which is the byte sequence (
\xc4\x80
) that representsĀ
in UTF-8. So if you useencodeURIComponent()
your server side must know that it is receiving UTF-8. Otherwise PHP will mangle the encoding.In JavaScript try:
and in PHP: