PHP cURL HTTP POST Example
In this article, we'll demonstrate how to send HTTP POST requests using PHP cURL.
Example Scenario:
We want to send the following data to www.example.com:
username=user1, password=passuser1, gender=1
and expect the cURL request to return a response like result=OK.
PHP Code Snippet:
// Initialize a cURL handle $ch = curl_init(); // Set the URL to post to curl_setopt($ch, CURLOPT_URL, "http://www.example.com/tester.phtml"); // Enable POST method curl_setopt($ch, CURLOPT_POST, true); // Set the POST fields $data = array('username' => 'user1', 'password' => 'passuser1', 'gender' => 1); $post_fields = http_build_query($data); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); // Receive server response curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch); // Close the cURL handle curl_close($ch); // Process the response if ($server_output == "OK") { // Handle successful response } else { // Handle error }
This PHP cURL example sends the specified data to the remote server using the HTTP POST method. The server's response is stored in the $server_output variable. You can then process the response accordingly, checking if it matches the expected result=OK or handling any errors.
The above is the detailed content of How to Send HTTP POST Requests Using PHP cURL?. For more information, please follow other related articles on the PHP Chinese website!