Sending a JSON string as a HTTP query parameter?

11,855

Solution 1

Use:

$string = urlencode(json_encode($array));

and using the

$array = urldecode(json_decode($string));

to decode the string back into a PHP array.

Solution 2

Instead of using JSON use http_build_query(). It's already URL encoded and it might save you some space if that's the issue. It also handles multidimensional arrays.

Share:
11,855
Kemebear
Author by

Kemebear

Updated on June 24, 2022

Comments

  • Kemebear
    Kemebear almost 2 years

    On a local version of a project I've been building, I've been sending a JSON string as a HTTP query parameter, and using the json_decode() function to decode the string back into a PHP array.

    Locally, this was working fine (XAMPP) however when I upload these files to my clients server, they no longer work. I have diagnosed this as an issue where the parameter for which the JSON string is passed as e.g. o=[{"b_id":"1","p_ref_id":"SHAY899","b_name":"John Smith"}] isn't picked up in the global $_GET array.

    I thought perhaps the version of PHP required to encode/decode JSON wasn't available, however I use the json_encode() in other parts of this project, so that can't be the issue. I'm wondering perhaps if it's a max character length issue, and if so how would I solve it (or where would I start at least)?

    If not, any other help would be very greatly appreciated!!

    • Mike Christensen
      Mike Christensen almost 11 years
      If it's a really long URL, it's likely you're running into some sort of limit. Also, many web services (and frameworks) prevent certain characters on the URL for security reasons, to defend against XSS attacks for example. It's strange you don't get any sort of HTTP error though.
    • Brad M
      Brad M almost 11 years
      Are you URL encoding your JSON string before making it a query string parameter?
    • Kemebear
      Kemebear almost 11 years
      @MikeChristensen How long would you say is a really long URL/where would this limit be set on a basic configuration (frameworkless) PHP, Apache or elsewhere?
    • Mike Christensen
      Mike Christensen almost 11 years
      I've seen 1024 characters as a default HTTP GET limit before. I don't know where that's set in Apache though..