Skip to content
Advertisement

How can I log the full body of a POST request to a file for debugging?

I’ve read many ‘possible duplicates’ of this question and have used the code from one of them in this post but I cannot seem to see exactly what this question is asking.

As part of a much bigger project unrelated to PHP or websites I need to obtain the body of a POST request to my shared server. Following the ideas from this SO post I have made a php file in the www folder on the server containing the following

webhook.php

JavaScript

I then used a third party company to POST a test message to that script on my server, which was received OK, with a 200 response.

The body of that post contained

JavaScript

but the log file on my server contains only

JavaScript

I’m not a PHP programmer (just do the minimum I need to in order to get the job done) For debugging and development purposes, how should I alter my webhook.php script so that I can see all the data that was sent?

If I can do that then I can probably work out how do do the proper processing on each element, which won’t always have the structure above.

Advertisement

Answer

PHP only populates $_POST, when the request Content-Type was either application/x-www-form-urlencoded or multipart/form-data. If you get send anything else, then you have to use php://input to read the raw POST body, and parse it yourself.

The example JSON you have shown appears to be valid – so if json_decode does not give you the expected result here, then your input data was probably not what you expected it to be in the first place.

A basic debugging mistake here is that you are only looking at the final result of multiple “compound” operations. Log what file_get_contents('php://input') returned first of all, to see if that actually is what you expected it to be. If it wasn’t to begin with, then looking only at what json_decode returned, isn’t that helpful.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement