Saturday, March 23, 2019

Sending JSON via POST in PHP and CURL usage

Sometimes, you’ll come across web services and APIs that will require you to send JSON via a POST request. The php code that you need:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<?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);
stolen from:  http://thisinterestsme.com/sending-json-via-post-php/

More Useful CURL tidbits of info.
https://gist.github.com/subfuzion/08c5d85437d5d4f00e58

curl usage to send POST 

For sending data with POST and PUT requests, these are common curl options:
  • request type
    • -X POST
    • -X PUT
  • content type header
  • -H "Content-Type: application/x-www-form-urlencoded"
  • -H "Content-Type: application/json"
  • data
    • form urlencoded: -d "param1=value1&param2=value2" or -d @data.txt
    • json: -d '{"key1":"value1", "key2":"value2"}' or -d @data.json


No comments:

Post a Comment