POSTing with cURL in PHP
In PHP, cURL can be leveraged for HTTP POST requests, allowing you to send data to a remote server.
Example:
Suppose you want to send the following data to www.example.com:
username=user1, password=passuser1, gender=1
And expect a "result=OK" response. Here's how to implement it:
$ch = curl_init(); // Set the POST URL curl_setopt($ch, CURLOPT_URL, "http://www.example.com/tester.phtml"); // Enable POST and set POST fields curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(['postvar1' => 'value1'])); // Receive the response and store it in a variable curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $server_output = curl_exec($ch); // Close the cURL connection curl_close($ch); // Process the response (e.g., check if the result is "OK") if ($server_output == "OK") { // Perform actions if the response matches the expected result } else { // Handle cases where the result is different }
This script initializes a cURL session ($ch), specifies the POST URL, enables POST, sets the POST data, and captures the server's response. If the response matches the expected "OK" result, specific actions can be performed accordingly.
The above is the detailed content of How Can I Use cURL in PHP to Make HTTP POST Requests?. For more information, please follow other related articles on the PHP Chinese website!