Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Json_encode changing spaces to plus symbols +

Tags:

json

jquery

php

I have a web app where I first store JSON data in a cookie, then save to the database every x seconds. It just opens a connection to the server, and the server reads the cookie. It doesn't actually send anything via POST or GET.

While I save to the cookie, my data is formatted fine. However, when I work with it in PHP then setcookie a new json_encoded array, it replaces spaces with + symbols, and then these show up in my web app. I can't find any way to disable encoding of strings for json_encode, nor a JS way of parsing those plus symbols out (using jQuery.parseJSON; stringify's parse didn't work either)... Does anyone have any idea :S?

like image 380
Benno Avatar asked Jul 25 '11 04:07

Benno


1 Answers

From the fine manual:

Note that the value portion of the cookie will automatically be urlencoded when you send the cookie, and when it is received, it is automatically decoded and assigned to a variable by the same name as the cookie name. If you don't want this, you can use setrawcookie() instead if you are using PHP 5.

But I think you still want the cookie URL encoded, you just want %20 for spaces instead of +. However, urlencode:

[...] for historical reasons, spaces are encoded as plus (+) signs

You could try using rawurlencode to encode it yourself:

Returns a string in which all non-alphanumeric characters except -_.~ have been replaced with a percent (%) sign followed by two hex digits. This is the encoding described in RFC 3986 [...]

And then setrawcookie to set the cookie. Unfortunately, none of decodeURI, decodeURIComponent, or even the deprecated unescape JavaScript functions will convert a + back to a space; so, you're probably stuck forcing everyone to make sense the hard way.

like image 200
mu is too short Avatar answered Nov 02 '22 03:11

mu is too short