When making a request with curl we can send post data as individual fields, such as when submitting a form,
or we can send the data as an one block of text.
The code examples below show how to send both types of requests with PHP.
These two code examples show how to send and receive data as individual fields.
<?php
$url = 'http://localhost/read_post_fields.php';
$data = array(
'field1' => 'value1',
'field2' => 'value2'
);
$query_string = http_build_query($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
<?php
$data = $_POST;
print_r($data);
These two code examples show how to send data as one block of text or "raw data", and how to receive it.
<?php
$url = 'http://localhost/read_post_raw_data.php';
$data = array(
'field1' => 'value1',
'field2' => 'value2'
);
$body = json_encode($data);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
<?php
$body = file_get_contents('php://input');
$data = json_decode($body);
print_r($data);