How To Send PHP cURL POST Request with JSON Parameters

Share this Article
Reading Time: 3 minutes
1,155 Views

Inside this article we will see the concept i.e How To Send cURL POST request with JSON parameters. This tutorial will give you the classified information about initiating cURL request in PHP using POST request.

cURL is a tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, FTPS, GOPHER, DICT, TELNET, LDAP or FILE)

For consuming fake apis, we will this OWT fakeAPIs.

Learn More –

Let’s get started.

Example: cURL POST Request

Create a file index.php inside your localhost directory. Open file and write this code into it.

<?php
// API URL
$url = 'https://api.onlinewebtutorblog.com/employees';

// POST Data
$data = array(
    "username" => "sanjay_owt",
    "name" => "Sanjay Kumar",
    "email" => "sanjay@example.net",
    "gender" => "male",
    "designation" => "Web Developer",
    "phone_number" => "1234567890",
    "complete_address" => "Sample location"
);

// Convert to JSON
$postdata = json_encode($data);

// Init cURL
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);

curl_close($ch);

// Output Result
echo "<pre>";
print_r($result);

Concept

API

// API URL
$url = 'https://api.onlinewebtutorblog.com/employees';

Add POST data

// POST Data
$data = array(
    "username" => "sanjay_owt",
    "name" => "Sanjay Kumar",
    "email" => "sanjay@example.net",
    "gender" => "male",
    "designation" => "Web Developer",
    "phone_number" => "1234567890",
    "complete_address" => "Sample location"
);

Sending JSON data

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

Application Testing

Now,

URL: http://localhost/php-curl/index.php

We hope this article helped you to Learn How To Send PHP cURL POST Request with JSON Parameters Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5