Here is a brief tutorial of PHP CURL Post Example to send JSON data. If you want to create a Rest of the PHP API without using any framework, I will give a short tutorial how to send JSON data PHP using curl and receive post data on the API server.
I have discussed how to create REST API using the slim framework in article “Rest API And HTTP Methods (GET, POST, PUT, DELETE) Using Slim Framework And PHP.” The way it is easy to apply. However, not all programmers use the framework. This time I will share PHP CURL Post Example without any framework help. Let’s follow this short tutorial.
Table of Contents
How to send JSON PHP data CURL post example and How to retrieve post data curl in server
- Create a project folder with the name “post“
- Create two pieces of PHP file with the name client.php and api.php
- Insert the following code to client.php123456789101112131415161718192021222324<?php$array = array();$product = array();$product[0]['id_product'] = 'A01';$product[0]['name_product'] = 'Sandal';$product[0]['price_product'] = '500';$product[1]['id_product'] = 'A02';$product[1]['name_product'] = 'Shoes';$product[1]['price_product'] = '2500';$array['id'] = '123';$array['note'] = 'this is my short example';$array['data'] = $product;$data = json_encode($array);$ch = curl_init('http://localhost/post/api.php');curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");curl_setopt($ch, CURLOPT_POSTFIELDS, $data);curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);curl_setopt($ch, CURLOPT_POST, count($data));$result = curl_exec($ch);var_dump($result);?>
- Insert the following code on api.php123456789101112<?php$fp = fopen('php://input', 'r');$raw = stream_get_contents($fp);$data = json_decode($raw,true);echo $data['id'];echo $data['note'];foreach ($data['data'] as $key) {echo 'id_product : '.$key['id_product'].'<br/>';echo 'name_product : '.$key['name_product'].'<br/>';echo 'price_product : '.$key['price_product'].'<br/>';}?>
Leave a Reply