Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 09-27-2012, 05:20 PM   PM User | #1
loamguy1
Regular Coder

 
Join Date: Nov 2007
Posts: 106
Thanks: 13
Thanked 0 Times in 0 Posts
loamguy1 is an unknown quantity at this point
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...
loamguy1 is offline   Reply With Quote
Old 10-05-2012, 03:14 PM   PM User | #2
loamguy1
Regular Coder

 
Join Date: Nov 2007
Posts: 106
Thanks: 13
Thanked 0 Times in 0 Posts
loamguy1 is an unknown quantity at this point
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);
loamguy1 is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:21 AM.


Advertisement
Log in to turn off these ads.