Last active
July 10, 2020 18:04
-
-
Save sivinnguyen/2067d431c61633acd6a013cb23c554fc to your computer and use it in GitHub Desktop.
POST and Receive JSON Data using PHP cURL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// More detail at https://www.codexworld.com/post-receive-json-data-using-php-curl | |
// API URL | |
$url = 'http://www.example.com/api'; | |
// Create a new cURL resource | |
$ch = curl_init($url); | |
// Setup request to send json via POST | |
$data = array( | |
'username' => 'xxx', | |
'password' => 'xxx' | |
); | |
$payload = json_encode($data); | |
// Attach encoded JSON string to the POST fields | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); | |
// Set the content type to application/json | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json')); | |
// Return response instead of outputting | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
// If run on localhost without ssl | |
// See https://stackoverflow.com/a/43207531/1813901 | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); | |
// Execute the POST request | |
$result = curl_exec($ch); | |
// Close cURL resource | |
curl_close($ch); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment