A few days ago I've been working a project which, as many other projects out there today, communicates with some external APIs. At some point, in order to perform some tests, I had to write an API endpoint within my project itself to fake the actual external API. I need to mention that the external API was expecting
application/json content type, so basically the
curl setup looked like this:
<?php //... $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_VERBOSE, true ); curl_setopt( $ch, CURLOPT_HEADER, true ); curl_setopt( $ch, CURLOPT_TIMEOUT, $this->timeout_limit ); curl_setopt( $ch, CURLOPT_ENCODING, '' ); curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 ); curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $data ) ); curl_setopt( $ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json' ) ); // ...
The issue was that when I've been trying to catch the POST data and use it, I was getting
null as a value for both
$_REQUEST, and I couldn't understand why 🤔. Apparently (and maybe many of you already knew that), if the data is sent as
application/x-www-form-urlencoded then yes, you can use PHP globals
$_REQUEST to catch and use that data. But, if the data is sent as
application/json, then prior to PHP 5.6 you could've use $HTTP_RAW_POST_DATA to grab the raw POST data, or (and based on PHP docs this is the preferable way to do it) use the php://input - a read-only stream that allows you to read raw data from the request body.
So, as a result I ended up grabbing the POST data like this:
<?php // receive the JSON Post data $data = json_decode( file_get_contents( 'php://input' ), true );
Big credits to these stackoverflow discussions:
Happy coding everyone! 💻 🤓 👍