How to Send a Post Request with PHP
In this snippet, we will share with you the most flexible and powerful ways of sending post requests with the help of PHP. Just check out the examples.
In this tutorial, we share three reliable ways to send POST requests using PHP.
Review the examples below and choose the one that best fits your project.
A. Using PHP cURL
The PHP cURL extension is a straightforward way to combine different flags with setopt() calls.
Below is an example using the $xml variable as a placeholder for the XML data you intend to send:
php curl
<?php
$url = 'http://api.flickr.com/services/xmlrpc/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if (curl_errno($ch)) {
echo 'cURL Error: ' . curl_error($ch);
} else {
// Process $response
}
curl_close($ch);
?>In this example, the connection is initialized first, followed by option configuration via setopt() . These settings instruct PHP to send a POST request.
B. Using Pecl_HTTP
Note: The pecl_http extension is obsolete and has been removed from modern PHP versions. For production projects, consider using Guzzle or the built-in cURL extension.
Generally, pecl_http object-oriented setopt() pecl_http :
php pecl_http
<?php
$url = 'http://api.flickr.com/services/xmlrpc/';
$response = http_post_data($url, $xml);
?>C. Using the Object-Oriented (OO) Interface of Pecl_HTTP
As noted above, the second interface of pecl_http object-oriented . It is similar to the extensions demonstrated above but applies a different interface. Here is how its code looks:
php pecl_http
<?php
$url = 'http://api.flickr.com/services/xmlrpc/';
$request = new HTTPRequest($url, HTTP_METH_POST);
$request->setRawPostData($xml);
$request->send();
$response = $request->getResponseBody();
?>Although this code is longer, it remains powerful and flexible. It can be a solid option for legacy projects.
Note: For production use, always add error handling (e.g., curl_error() or try/catch) and parse the response appropriately.
D. Modern Alternative: Guzzle HTTP Client
For modern PHP projects, third-party libraries like Guzzle provide a cleaner, more maintainable approach to HTTP requests. Here is a basic example:
php guzzle
<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('http://api.flickr.com/services/xmlrpc/', [
'body' => $xml
]);
echo $response->getBody();
?>