Home > Backend Development > PHP Tutorial > How Can I Use PHP cURL to Send an HTTP POST Request?

How Can I Use PHP cURL to Send an HTTP POST Request?

Linda Hamilton
Release: 2024-12-24 03:08:19
Original
429 people have browsed it

How Can I Use PHP cURL to Send an HTTP POST Request?

PHP cURL with HTTP POST

Introduction

cURL is a library used in PHP for transferring data over a network. One common use case for cURL is to send HTTP POST requests. This article provides an example of how to use cURL in PHP to send an HTTP POST request to a remote site.

Problem

A user needs to send data to a remote site using an HTTP POST request. The data includes username, password, and gender. The user expects a response from the remote site indicating whether the operation was successful.

Solution

To send an HTTP POST request using cURL in PHP, follow these steps:

// Initialize a cURL handle
$ch = curl_init();

// Set the URL to which the request should be sent
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/tester.phtml");

// Specify that the request is a POST request
curl_setopt($ch, CURLOPT_POST, true);

// Set the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, 
          http_build_query(array('username' => 'user1', 'password' => 'passuser1', 'gender' => 1)));

// Receive server response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request and get the server response
$server_output = curl_exec($ch);

// Close the cURL handle
curl_close($ch);

// Further processing
if ($server_output == "OK") { ... } else { ... }
Copy after login

This script will send a POST request to the specified URL with the provided data. The server response is stored in the $server_output variable and can be further processed as needed.

The above is the detailed content of How Can I Use PHP cURL to Send an HTTP POST Request?. 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