Home >Backend Development >PHP Tutorial >How to Perform an HTTP POST Request Using PHP's cURL Library?

How to Perform an HTTP POST Request Using PHP's cURL Library?

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 17:47:13429browse

How to Perform an HTTP POST Request Using PHP's cURL Library?

PHP, cURL, and HTTP POST

This question seeks guidance on performing an HTTP POST request using PHP's cURL library. Specifically, the goal is to send data in a specific format to a specified website and receive a response.

Solution:

To achieve this, the provided code example provides a step-by-step guide on how to set up and execute a cURL POST request. It initializes a cURL session, specifies the target URL, sets POST parameters, and finally sends the request. The code also includes error handling and provides a simple example of processing the server's response.

The code snippet below shows the PHP code for the solution:

//
// 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 { ... }

By following these steps, you can successfully perform an HTTP POST request using PHP's cURL library.

The above is the detailed content of How to Perform an HTTP POST Request Using PHP's cURL Library?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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