PHP - Send JSON Data Via POST

From myWiki
Revision as of 10:19, 23 August 2018 by Stevet (talk | contribs) (Created page with "<syntaxhighlight lang="php" line='line'> <?php //API Url $url = 'http://example.com/api/JSON/create'; //Initiate cURL. $ch = curl_init($url); //The JSON data. $jsonData...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
<?php
 
//API Url
$url = 'http://example.com/api/JSON/create';
 
//Initiate cURL.
$ch = curl_init($url);
 
//The JSON data.
$jsonData = array(
    'username' => 'MyUsername',
    'password' => 'MyPassword'
);
 
//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')); 
 
//Execute the request
$result = curl_exec($ch);

http://thisinterestsme.com/sending-json-via-post-php/