D
D
Denis D.2014-07-15 18:56:59
PHP
Denis D., 2014-07-15 18:56:59

Where do escape slashes come from when sending JSON to PHP?

Came across one feature in PHP.

Let's say we want to send some data in json format to the server using the GET method. For example, we have data:

var data = {
    "value1" : "key1",
    "value2" : "key2"
}

We send them to the server using the GET method:
function doXHR (data) {
  var xhr = getXMLHttpRequest(),
            json = encodeURIComponent(JSON.stringify(data));
  xhr.open('GET', 'http://domain.com/?json=' + json, true);
  xhr.send();
  xhr.onreadystatechange = function (e) {
    console.log(e);
  };
}

This is where things get interesting. When we try to access the variable on the server, we will see that an escape slash has appeared before each quote, so it is quite logical that decoding will cause an error:
print_r($_GET['json']);  // => {\"value1\":\"key\",\"value2\":\"key2\"}
print_r(json_decode($_GET['json'])); // => NULL
print_r(json_last_error()); // => 4

I got out of the situation simply by removing all slashes with the stripcslashes() function; . but I'm still wondering where the escape characters came from.
From everything I found a topic on HashCode with a similar problem, but the author also got out of the situation by manually removing the slashes with the replace () function; .

What's the catch? Is it the browser, or is the server escaping quotes, or is it a UFO? Can problems be solved in a more natural way?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey, 2014-07-15
@denysd

magic_quotes ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question