Skip to content

Instantly share code, notes, and snippets.

@sivinnguyen
Last active July 10, 2020 18:04
Show Gist options
  • Save sivinnguyen/2067d431c61633acd6a013cb23c554fc to your computer and use it in GitHub Desktop.
Save sivinnguyen/2067d431c61633acd6a013cb23c554fc to your computer and use it in GitHub Desktop.
POST and Receive JSON Data using PHP cURL
<?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