Home >Backend Development >PHP Tutorial >How to Perform an HTTP POST Request Using PHP cURL?
PHP cURL HTTP POST Example
When working with web applications, it's often necessary to send HTTP requests to remote servers. In PHP, the cURL extension provides a powerful and versatile way to accomplish this. This article demonstrates how to perform an HTTP POST using PHP cURL.
Problem Statement
Suppose we want to send the following data to www.example.com:
username=user1, password=passuser1, gender=1
The expected response from the server is "result=OK".
PHP cURL Solution
To send an HTTP POST request with PHP cURL, follow these steps:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/tester.phtml");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('postvar1' => 'value1')));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch);
curl_close($ch);
if ($server_output == "OK") { ... } else { ... }
Code Example
Here's a complete PHP example that demonstrates the above steps:
// A very simple PHP example that sends a HTTP POST to a remote site $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.example.com/tester.phtml"); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('postvar1' => 'value1'))); // Receive server response ... curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch); curl_close($ch); // Further processing ... if ($server_output == "OK") { ... } else { ... }
The above is the detailed content of How to Perform an HTTP POST Request Using PHP cURL?. For more information, please follow other related articles on the PHP Chinese website!