This PHP example program demonstrates four ways to send and receive JSON data.
<?php echo "Relevant variables:<hr />"; echo '$_SERVER["HTTPS"] = '.$_SERVER['HTTPS']."<br />"; echo '$_SERVER["HTTP_HOST"] = '.$_SERVER['HTTP_HOST']."<br />"; echo '$_SERVER["SERVER_NAME"] = '.$_SERVER['SERVER_NAME']."<br />"; echo '$_SERVER["SERVER_PORT"] = '.$_SERVER['SERVER_PORT']."<br />"; echo 'dirname($_SERVER["PHP_SELF"]) = '.dirname($_SERVER["PHP_SELF"])."<br />"; /* // To see all of the server values, use this loop or call phpinfo(); foreach ($_SERVER as $sIndex => $sValue) { echo '$_SERVER["'.$sIndex.'"] = '.$sValue."<br />"; } */ $qsData = array( 'user' => 'XoaX', 'id' => 1, ); $qPostOptions = array( 'http' => array( 'method' => 'POST', 'content' => json_encode( $qsData ), 'header'=> "Content-Type: application/json\r\n" . "Accept: application/json\r\n" ) ); // Set the protocol if (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) == 'on' || $_SERVER['HTTPS'] == '1')) { $sProtocol = 'https'; } else { $sProtocol = 'http'; } $sUrlBase = $sProtocol."://".$_SERVER['SERVER_NAME'].":".$_SERVER['SERVER_PORT'].dirname($_SERVER["PHP_SELF"]); // ************** FIRST REQUEST ************** echo "<br /><br /><br />First request (using file_get_contents('php://input')):<hr />"; // Create the URL for this directory and the file that we are contacting $sUrl1 = $sUrlBase."/PostJsonResponse1.php"; echo "First URL = ".$sUrl1."<br />"; // Make the post request $qContext = stream_context_create( $qPostOptions ); //Note that this won't work if the allow_url_fopen setting is set to Off in the php.ini file. $sResult = file_get_contents( $sUrl1, false, $qContext ); // Display the result string echo "The response result #1 was ".$sResult."<br />"; $qResponse = json_decode( $sResult ); // Display the decoded object echo "<pre>".json_encode($qResponse, JSON_PRETTY_PRINT)."</pre>"; // ************** SECOND REQUEST ************** echo "<br /><br /><br />Second request (using \$_POST):<hr />"; // Create the URL for this directory and the file that we are contacting $sUrl2 = $sUrlBase."/PostJsonResponse2.php"; echo "Second URL = ".$sUrl2."<br />"; $qPostOptions['http']['content'] = "json=".json_encode( $qsData ); // NOTE: The type must application/x-www-form-urlencoded for the $_POST variable to be filled $qPostOptions['http']['header'] = "Content-Type: application/x-www-form-urlencoded\r\n"."Accept: application/json\r\n"; // Make the post request $qContext = stream_context_create( $qPostOptions ); $sResult = file_get_contents( $sUrl2, false, $qContext ); // Display the result string echo "The response result #2 was ".$sResult."<br />"; $qResponse = json_decode( $sResult ); // Display the decoded object echo "<pre>".json_encode($qResponse, JSON_PRETTY_PRINT)."</pre>"; // ************** THIRD REQUEST ************** echo "<br /><br /><br />Third request (using Curl):<hr />"; // Reuse the first URL for the third call echo "Third URL = ".$sUrl1."<br />"; $qCurl = curl_init($sUrl1); curl_setopt($qCurl, CURLOPT_RETURNTRANSFER, true); curl_setopt($qCurl, CURLOPT_CUSTOMREQUEST, "POST"); curl_setopt($qCurl, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); curl_setopt($qCurl, CURLOPT_POST, true); curl_setopt($qCurl, CURLOPT_POSTFIELDS, json_encode($qsData)); $sResult = curl_exec($qCurl); curl_close($qCurl); // Display the result string echo "The response result #3 was ".$sResult."<br />"; $qResponse = json_decode( $sResult ); // Display the decoded object echo "<pre>".json_encode($qResponse, JSON_PRETTY_PRINT)."</pre>"; // ************** FOURTH REQUEST ************** echo "<br /><br /><br />Fourth request (using http_build_query() and \$_POST):<hr />"; // Reuse the second URL for the third call echo "Fourth URL = ".$sUrl2."<br />"; $aPairs = ['json' => json_encode( $qsData )]; $qPostOptions['http']['content'] = http_build_query($aPairs); // Make the post request $qContext = stream_context_create( $qPostOptions ); $sResult = file_get_contents( $sUrl2, false, $qContext ); // Display the result string echo "The response result #4 was ".$sResult."<br />"; $qResponse = json_decode( $sResult ); // Display the decoded object echo "<pre>".json_encode($qResponse, JSON_PRETTY_PRINT)."</pre>"; ?>
<?php // Retrieve the raw POST data $sJsonData = file_get_contents('php://input'); // Decode the JSON data into a PHP associative array $qJsonObject = json_decode($sJsonData, true); // Check if decoding was successful if ($qJsonObject !== null) { // Access the data and perform operations $sName = $qJsonObject['user']; $iId = $qJsonObject['id']; $qReturnedObject = new stdClass(); // Change the values before we return it. $qReturnedObject->name = $sName.".net"; $qReturnedObject->value = $iId + 1; // Encode and return the Json string of the object $sReturnedJSON = json_encode($qReturnedObject); echo $sReturnedJSON; } else { // The JSON decoding failed, return a 400 bad request http_response_code(400); echo "Invalid JSON data"; } ?>
<?php // This takes the request as urlencoded data. This is required for the $_POST to be filled. // Retrieve the raw POST data $sJsonData = $_POST; // Make sure that the data is available if (!empty($sJsonData)) { $Json = $_POST['json']; $qObject = json_decode($Json, true); // Access the data and perform operations $sName = $qObject['user']; $iId = $qObject['id']; $qReturnedObject = new stdClass(); // Change the values before we return it. $qReturnedObject->name = $sName.".net 2"; $qReturnedObject->value = $iId + 2; // Encode and return the Json string of the object $sReturnedJSON = json_encode($qReturnedObject); echo $sReturnedJSON; } else { // The JSON decoding failed, return a 400 bad request http_response_code(400); echo "Error: The data must be urlencoded data for $_POST to be fillled."; } ?>
© 20072025 XoaX.net LLC. All rights reserved.