PHP: Curl Post Fields or Raw data

November 29, 2020

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.


Using Curl to Post Fields

These two code examples show how to send and receive data as individual fields.

send_post_fields.php


<?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);

read_post_fields.php


<?php
$data = $_POST;

print_r($data);

Using Curl to Post Raw Data

These two code examples show how to send data as one block of text or "raw data", and how to receive it.

send_post_raw_data.php


<?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);

read_post_raw_data.php


<?php
$body = file_get_contents('php://input');
$data = json_decode($body);

print_r($data);