How pass json data in url using curl in php?

First,

  1. always define certificates with CURLOPT_CAPATH option,

  2. decide how your POSTed data will be transfered.

1 Certificates

By default:

  • CURLOPT_SSL_VERIFYHOST == 2 which "checks the existence of a common name and also verify that it matches the hostname provided" and

  • CURLOPT_VERIFYPEER == true which "verifies the peer's certificate".

So, all you have to do is:

const CAINFO = SERVER_ROOT . '/registry/cacert.pem';
...
\curl_setopt($ch, CURLOPT_CAINFO, self::CAINFO);

taken from a working class where SERVER_ROOT is a constant defined during application bootstraping like in a custom classloader, another class etc.

Forget things like \curl_setopt($handler, CURLOPT_SSL_VERIFYHOST, 0); or \curl_setopt($handler, CURLOPT_SSL_VERIFYPEER, 0);.

Find cacert.pem there as seen in this question.

2 POST modes

There are actually 2 modes when posting data:

  • the data is transfered with Content-Type header set to multipart/form-data or,

  • the data is a urlencoded string with application/x-www-form-urlencoded encoding.

In the first case you pass an array while in the second you pass a urlencoded string.

multipart/form-data ex.:

$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);

application/x-www-form-urlencoded ex.:

$fields = array('a' => 'sth', 'b' => 'else');
$ch = \curl_init();
\curl_setopt($ch, CURLOPT_POST, 1);
\curl_setopt($ch, CURLOPT_POSTFIELDS, \http_build_query($fields));

http_build_query:

Test it at your command line as

[email protected]:$ php -a
php > $fields = array('a' => 'sth', 'b' => 'else');
php > echo \http_build_query($fields);
a=sth&b=else

The other end of the POST request will define the appropriate mode of connection.


In this article, you will learn how to post JSON data using cURL in PHP. cURL command is usually used to transfer data to and from a server.

Post JSON Data Using cURL

In order to post JSON data using cURL, you can use the curl_init() method, curl_setopt() method, curl_exec() method, and curl_close() method.

$data = array(
    "name" => "John",
    "email" => "[email protected]"
);
 
// Convert the PHP array into a JSON format
$payload = json_encode($data);
 
// Initialise new cURL session
$ch = curl_init('https://api.creativecommons.engineering/v1/auth_tokens/register');

// Return result of POST request
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Get information about last transfer
curl_setopt($ch, CURLINFO_HEADER_OUT, true);

// Use POST request
curl_setopt($ch, CURLOPT_POST, true);

// Set payload for POST request
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
 
// Set HTTP Header for POST request 
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'Content-Length: ' . strlen($payload))
);
 
// Execute a cURL session
$result = curl_exec($ch);
 
// Close cURL session
curl_close($ch);

Note: The curl_init() method functions by initialising a new cURL session. The curl_setopt() method functions by setting options for a cURL session handle. The curl_exec() method functions by executing a cURL session. The curl_close() method functions by closing a cURL session to free up resources.

Share on social media

//

PreviousNext

How pass json data in url using curl in php?

In this article you will learn about how to create web services APIs using PHP. Iif you are working with web services, you need to know about how we can POST and Receive JSON Data using cURL in PHP. Sending and Receiving JSON data via POST Request is most important functionality in PHP. It’s make easy to POST JSON data to APIs url and receive response in JSON data format. So, Today we will learn about “How to POST and Receive JSON Data using cURL in PHP”.

  • Let’s Start to send JSON data via POSt Request with PHP cURL:
  •  index.php
  • test.php

Let’s Start to send JSON data via POSt Request with PHP cURL:

In the following example code, i will show you HTTP POST request and send JSON data to URL with cURL function.

Step-1: First we will specify URL ($url)where the JSON data need to be send.
Step-2: Initiate cURL resource using curl_init().
step-3: encode PHP array data into aJSON string using json_encode().
step-4: Attach JSON data to the POSt field using the CURLOPT_POSTFIELDS option.
step-5: set header option to Content-Type: application/json
step-6: Return response as string CURL_RETURNTRANSFER option
Step-7: Finally curl_exec() function is used to execute the POST request api url.

 index.php

In the following example code, We will pass POST data on API URL as JSON format.

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

<?php

$id=120;

$name="Tutorialswebsite";

$address="Sultanpur, New Delhi";

$phone=9999999999;

//API URL

$url="localhost/doctopdf/test.php";

$data =array("id"=>$id,"name"=>$name,"address"=>$address,"phone"=>$phone);

$ch=curl_init($url);

# Setup request to send json via POST.

$payload=json_encode(array("customer"=>$data ));

curl_setopt($ch,CURLOPT_POSTFIELDS,$payload);

curl_setopt($ch,CURLOPT_CUSTOMREQUEST,"POST");

curl_setopt( $ch,CURLOPT_HTTPHEADER,array('Content-Type:application/json'));

# Return response instead of printing.

curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);

# Send request.

$result=curl_exec($ch);

curl_close($ch);

# Print response.

echo"<pre>".$result."</pre>";

?>

test.php

In the following code, We will Receive JSON POST data using PHP

jsone_decode() function is used to decode JSON data into array format and file_get_content() function is used to receivedata in readable format

<?php

header("Content-Type:application/json");

$data=json_decode(file_get_contents('php://input'),true);

print_r($data);

?>

Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request

How pass json data in url using curl in php?

Pradeep Maurya is the Professional Web Developer & Designer and the Founder of  “Tutorials website”. He lives in Delhi and loves to be a self-dependent person. As an owner, he is trying his best to improve this platform day by day. His passion, dedication and quick decision making ability to stand apart from others. He’s an avid blogger and writes on the publications like Dzone, e27.co

Post navigation

How pass JSON data in cURL Post?

To post JSON data using Curl, you need to set the Content-Type of your request to application/json and pass the JSON data with the -d command line parameter. The JSON content type is set using the -H "Content-Type: application/json" command line parameter. JSON data is passed as a string.

How get JSON data from API URL in PHP?

Use the file_get_contents() Function to Get JSON Object From the URL in PHP. We can use file_get_contents() along with json_decode() to get the JSON object from a URL. The file_get_contents() function reads the file in a string format.

How cURL URL in PHP?

php file with the following contents. $url = 'https://www.example.com' ; $curl = curl_init(); curl_setopt( $curl , CURLOPT_URL, $url );

Does cURL use JSON?

by David Callaghan on January 20th, 2022 | ~ 3 minute read cURL is frequently used by developers working with REST API's to send and receive data using JSON notation.

Tải thêm tài liệu liên quan đến bài viết How pass json data in url using curl in php?