Question
How can I send an HTTP POST request in PHP using cURL?
I want to send form-style data like this:
username=user1password=passuser1gender=1
The request should be sent to www.example.com, and I expect the server to return a response such as result=OK.
What is a simple PHP cURL example that shows how to send this data and read the response?
Short Answer
By the end of this page, you will understand how to use PHP cURL to send an HTTP POST request, attach form data, receive the response, and handle common mistakes such as forgetting CURLOPT_RETURNTRANSFER or posting data in the wrong format.
Concept
In PHP, cURL is a library used to make HTTP requests from your code. It is commonly used to talk to APIs, submit forms programmatically, send login data, upload files, or communicate with other web services.
An HTTP POST request sends data to a server in the request body. This is different from a GET request, which usually sends data in the URL.
When you use cURL in PHP for a POST request, you usually do these things:
- Initialize a cURL session.
- Set the target URL.
- Tell cURL to use the POST method.
- Attach the data you want to send.
- Ask cURL to return the response as a string.
- Execute the request.
- Close the cURL session.
This matters in real programming because many systems require server-to-server communication. For example:
- submitting payment details to a gateway
- logging in to an external service
- sending form data to an API
- posting JSON or form fields to another application
For your example, the data looks like standard form fields, so the most common format is application/x-www-form-urlencoded, which is what regular HTML forms use by default.
Mental Model
Think of a cURL POST request like mailing a form to an office.
- The URL is the office address.
- The POST method means you are sending information inside the envelope.
- The POST fields are the form values you put in the envelope.
- The response is the letter the office sends back.
In PHP, cURL is the mail carrier. You tell it where to go, what method to use, what data to carry, and whether you want the reply handed back to your code.
Syntax and Examples
The basic PHP cURL POST pattern looks like this:
<?php
$url = 'https://www.example.com';
$data = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => '1'
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
echo 'cURL error: ' . curl_error($ch);
} else {
echo $response;
}
curl_close($ch);
What this code does
Step by Step Execution
Consider this example:
<?php
$data = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => '1'
];
$ch = curl_init('https://www.example.com');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
Step by step
-
PHP creates an array named
$data.- It contains three fields:
username,password, andgender.
- It contains three fields:
Real World Use Cases
PHP cURL POST requests are used in many practical situations:
-
Submitting login credentials
- Send a username and password to an authentication endpoint.
-
Calling third-party APIs
- Send search parameters, order details, or customer data to another service.
-
Webhook delivery
- Post event data from your application to another system.
-
Payment and billing integrations
- Send checkout or transaction data securely to a payment provider.
-
Internal microservice communication
- One backend service sends data to another backend service.
-
Form automation
- Simulate a form submission without a browser.
Example scenario:
<?php
$data = [
'email' => 'customer@example.com',
'plan' => 'pro'
];
This kind of data might be posted to a subscription API when a user upgrades their account.
Real Codebase Usage
In real projects, developers usually wrap cURL logic in reusable functions or service classes instead of writing raw cURL code everywhere.
Common patterns
-
Validation before sending
- Check required fields before making the request.
-
Guard clauses
- Return early if important data is missing.
-
Error handling
- Handle cURL errors and bad HTTP status codes separately.
-
Configuration-driven URLs
- Store API base URLs in config files or environment variables.
-
Response parsing
- Convert JSON responses into arrays with
json_decode().
- Convert JSON responses into arrays with
-
Timeouts
- Prevent requests from hanging too long.
Example helper function
<?php
function postForm(string $url, array $data): array
{
if (empty($url)) {
[ => , => ];
}
= ();
(, CURLOPT_POST, );
(, CURLOPT_POSTFIELDS, ());
(, CURLOPT_RETURNTRANSFER, );
(, CURLOPT_TIMEOUT, );
= ();
= ();
= (, CURLINFO_HTTP_CODE);
();
( === ) {
[ => , => ];
}
( >= ) {
[ => , => . , => ];
}
[ => , => ];
}
Common Mistakes
Here are some common beginner mistakes when using PHP cURL for POST requests.
1. Forgetting CURLOPT_RETURNTRANSFER
Broken code:
<?php
$ch = curl_init('https://www.example.com');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'username=user1');
$response = curl_exec($ch);
Problem:
- The response may be printed directly instead of stored properly.
$responsemay betrueinstead of the actual response body.
Fix:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
2. Sending an array when the server expects URL-encoded form data
Sometimes this works, but not always in the format you expect.
Safer approach:
(, CURLOPT_POSTFIELDS, ());
Comparisons
Here is a quick comparison of related request formats and options.
| Concept | What it does | Best for | Example |
|---|---|---|---|
| GET | Sends data in the URL | Reading data | example.com?username=user1 |
| POST | Sends data in the request body | Submitting data | login forms, API writes |
application/x-www-form-urlencoded | Standard form encoding | Simple form fields | username=user1&gender=1 |
application/json | Sends JSON text | Modern APIs | {"username":"user1"} |
Cheat Sheet
<?php
$data = [
'username' => 'user1',
'password' => 'passuser1',
'gender' => '1'
];
$ch = curl_init('https://www.example.com');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
if ($response === false) {
echo curl_error($ch);
} else {
echo $response;
}
curl_close($ch);
Quick rules
- Use
curl_init()to start. - Use
CURLOPT_POSTfor POST requests.
FAQ
How do I send POST data with PHP cURL?
Use CURLOPT_POST to enable POST and CURLOPT_POSTFIELDS to send the data.
How do I get the response body instead of printing it directly?
Set CURLOPT_RETURNTRANSFER to true. Then curl_exec() returns the response as a string.
Should I pass an array or use http_build_query()?
For simple form fields, http_build_query() is usually the safest and clearest choice.
How do I know whether the request failed?
Check whether curl_exec() returns false, then read the error with curl_error($ch).
Can I send JSON instead of form data?
Yes. Use json_encode() and set the Content-Type: application/json header.
Why is my server not receiving the posted values?
Common causes include using the wrong content type, forgetting http_build_query(), using the wrong URL, or sending to an endpoint that expects a different format.
Mini Project
Description
Build a small PHP script that submits a mock registration form to a remote endpoint using cURL. This project demonstrates how to collect form-style values in an array, encode them properly, send them with an HTTP POST request, and inspect the response and status code.
Goal
Create a reusable PHP script that sends form data with cURL and prints either a clear error message or the server response.
Requirements
- Create a PHP array with at least
username,password, andgender. - Send the data to a URL using an HTTP POST request.
- Encode the data as standard form data.
- Return and display the response body.
- Display a useful error message if the request fails.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.