Home > Backend Development > PHP Tutorial > How to Send HTTP POST Requests Using PHP cURL?

How to Send HTTP POST Requests Using PHP cURL?

Patricia Arquette
Release: 2024-12-27 20:07:10
Original
473 people have browsed it

How to Send HTTP POST Requests Using PHP cURL?

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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template