The code below shows an example of how to send data to another URL and also receive data in response via PHP. The communication is done using CURL and data is in the JSON format.
The Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
<?php ///BEGIN CODE FOR SEND.PHP //API Url where you want to receive the data $url = 'https://www.yourwebsite.com/receive.php'; //Initiate cURL. $ch = curl_init($url); #curl_setopt($ch, CURLOPT_USERPWD, "myusename:mypassword"); //set a basic auth user/pass if needed //The JSON data. $jsonData = array( 'string1' => 'this is a string from send.php', 'string2' => 'this is another string from send.php' ); #more variables could be added like this //$jsonData['string3'] = 'some other message'; //Encode the array into JSON. $jsonDataEncoded = json_encode($jsonData); //Tell cURL that we want to send a POST request. curl_setopt($ch, CURLOPT_POST, 1); //Attach our encoded JSON string to the POST fields. curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); //Set the content type to application/json curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); //Send a response back to this page curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //Execute the request $result = curl_exec($ch); curl_close($ch); $decoded = json_decode($result, true); //this prints out 'this is a string from send.php and now the string has been modified via receive.php' echo $decoded["response_string1"]; echo "<br>"; //this prints out 'this is another string from send.php and now the string has been modified via receive.php' echo $decoded["response_string2"]; //END CODE FOR SEND.PHP ?> <?php ///BEGIN CODE FOR RECEIVE.PHP //Receive the RAW post data. $content = trim(file_get_contents("php://input")); //Attempt to decode the incoming RAW post data from JSON. $decoded = json_decode($content, true); //If json_decode failed, the JSON is invalid. if(!is_array($decoded)){ throw new Exception('Received content contained invalid JSON!'); } $response["response_string1"] = $decoded["string1"] . " and now the string has been modified via receive.php"; $response["response_string2"] = $decoded["string2"] . " and now the string has been modified via receive.php"; echo json_encode($response); //END CODE FOR RECEIVE.PHP ?> |