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

How to Perform an HTTP POST Request Using PHP cURL?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 20:47:18616browse

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:

  1. Initialize a cURL session using curl_init():
$ch = curl_init();
  1. Set the URL of the remote server using curl_setopt():
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/tester.phtml");
  1. Indicate that this is an HTTP POST request using CURLOPT_POST:
curl_setopt($ch, CURLOPT_POST, true);
  1. Build the POST data using http_build_query() and set it using CURLOPT_POSTFIELDS:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('postvar1' => 'value1')));
  1. Fetch the server response using curl_exec() and set CURLOPT_RETURNTRANSFER to true:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec($ch);
  1. Close the cURL session using curl_close():
curl_close($ch);
  1. Process the server response as desired:
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!

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