How to use PHP to submit a cURL request with HTTP Post data

Posted in PHP on 28 October 2016

Straight forward script to POST an array of fields to a given URL.

// First, set the URL you want to POST the data to
$url = 'http://domain.com/script/';

// Specify the POST data
$fields = array(
  'field1' => "Value 1",
  'field2' => "Value Two",
  'field3' =>  "Value 3"
);


// Next, erge the array data into a single sting
foreach ($fields as $key => $value) { $fields_string .= $key . '=' . $value . '&'; }
$fields_string = "";
rtrim($fields_string, '&');

// Open a CURL connection
$ch = curl_init();

// Set the CURL options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);

// Fire!
$result = htmlspecialchars_decode(curl_exec($ch));

// Close your connection
curl_close($ch);

And that’s it. The $result variable will contain the response from the request. Depending how this is provided it might be plain text, JSON or pretty much anything else imaginable (over HTTP).

If it is a JSON string it can be converted to an object as follows:

$decode = json_decode($result);

Where $decode is a PHP object.

Related PHP Posts

March 2024

PHP Security in 2024: navigating the evolving landscape

As PHP continues to evolve, so do the threats that target its vulnerabilities. Ensuring robust PHP security practices is paramount to safeguarding sensitive data and... Continue reading

August 2021

Google Sheets to PHP Array

This PHP function accepts a public Google Sheets URL and converts it into a PHP array. You can use the array to either display the... Continue reading

March 2021

PHP cURL Requests with JSON or XML

The following post will explain how to use PHP/cURL to retrieve data in JSON or XML and process it for using in your PHP application... Continue reading

More PHP Posts