Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder
    Join Date
    Nov 2007
    Posts
    108
    Thanks
    14
    Thanked 0 Times in 0 Posts

    Processing POST variable in PHP REST service

    I'm testing my new PHP REST web service via localhost (http://localhost/myservice.php). It should accept both GET(retrieve info for one user) and POST requests(updates one user's preferences) via jQuery AJAX.

    Testing the GET functionality in the service is working great. I'm passing in a JSON structure and passing another back.

    However, I'm having trouble with the same service processing a POST request. It should accept JSON as the input. The code is correctly recognizing the request was a POST, not a GET, but the actual $_POST array is empty.

    I tried two different REST clients to test my service - POSTMAN and cREST. Both apps give me the same empty POST array. For testing I'm just outputing the POST array in the REST service which shows:

    Array
    (
    )

    One interesting tidbit: For debugging, I displayed 'php://input' which showed the POST variables were passed, but the actual $_POST array is empty.

    Has anyone had this problem before? I checked out several REST tutorials online, and haven't been able to find out any information on this issue.

    Any ideas welcome of course...

  • #2
    Regular Coder
    Join Date
    Nov 2007
    Posts
    108
    Thanks
    14
    Thanked 0 Times in 0 Posts
    Eventually found the solution to this:

    If you use JSON in a POST to a REST service, the JSON object is not treated as a valid query string. So, the POST array will exist, but it will be empty.

    Here is the work-around:

    $post_vars = file_get_contents('php://input');

    // Second parm TRUE, decodes into associative array
    $data = json_decode($post_vars, TRUE);


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •