How to use PHP to submit a cURL request with HTTP Post data
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.
Ready to elevate your website?
Whether you're launching a new site, strengthening security, or adding a new feature, I can help transform your vision into a high-performing online presence.
More Website Development posts
—
Structured data for SEO
Adding structured data to a website is one of those steps that often gets overlooked, yet it can make a real difference to how a site performs in search engines.…
—
Ensuring a smooth deployment of a PHP website application
Deploying a PHP website application requires meticulous planning, a solid understanding of the environment, and a thorough execution process. To ensure a smooth deployment, it is essential to follow best…
Continue reading "Ensuring a smooth deployment of a PHP website application"
—
Knack API Integration
Knack is a powerful low-code platform that allows you to build online databases and custom web applications. When integrating Knack with your own systems or custom front ends, you can…
—
Popular PHP frameworks
Here’s detailed look at some of the most popular PHP frameworks, each of which can help speed up development, improve code organisation, and enhance application performance. Laravel Laravel is one…