Question
I want to retrieve the response content from a URL after submitting a search request. The issue is that the URL only accepts POST requests and does not respond properly to GET requests.
I need to read the returned content in PHP, possibly using tools like DOMDocument or file_get_contents() after the request is made.
Is there a way to send parameters using the POST method in PHP and then read the returned content?
For example, the goal is similar to this:
<?php
// Send POST data to a URL
// Then read the returned HTML or response body
?>
Short Answer
By the end of this page, you will understand how to send a POST request in PHP, include form parameters, and read the server's response. You will also learn the most common approaches: cURL and stream contexts with file_get_contents(), when to use each one, and how to process the returned content afterward.
Concept
In web programming, a POST request sends data to a server in the body of the HTTP request rather than in the URL.
This matters because many websites and APIs:
- accept search forms only through
POST - require hidden form fields or credentials
- expect request headers such as
Content-Type - return HTML, JSON, or other content only after valid POST data is submitted
In PHP, reading a remote page with file_get_contents() by itself usually performs a simple GET request. If the server expects POST, you must explicitly tell PHP to send the request as POST and include the data.
There are two common ways to do this:
- cURL: the most flexible and widely used option
file_get_contents()with a stream context: simpler, but less powerful
After the response is returned, you can:
- print it directly
- parse HTML with
DOMDocument - decode JSON with
json_decode() - search or extract specific content
So the key idea is:
- build the POST data
- send the request using a PHP HTTP client mechanism
- capture the response body
- process the returned content
Mental Model
Think of a POST request like filling out a paper form and handing it to a receptionist.
- A GET request is like asking a question out loud: the information is visible in the URL.
- A POST request is like writing your details on a form and placing it in an envelope: the data is sent in the request body.
- The response is what the receptionist gives back after processing your form.
In PHP, file_get_contents() alone is like walking up and asking out loud. If the server only accepts forms, you need to package your data properly using a POST request.
Syntax and Examples
Using cURL
cURL is the most common way to send POST requests in PHP.
<?php
$url = 'https://example.com/search';
$data = [
'query' => 'php',
'category' => 'books'
];
$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);
}
curl_close($ch);
echo $response;
What this does
curl_init($url)prepares a request to the target URL
Step by Step Execution
Consider this example:
<?php
$url = 'https://example.com/search';
$data = [
'query' => 'laptop'
];
$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);
curl_close($ch);
echo $response;
Step-by-step
-
Create the target URL
$urlstores the address you want to send the request to.
-
Prepare the POST data
$datais an associative array.- It contains one field:
query=laptop.
Real World Use Cases
POST requests are extremely common in real applications.
Form submission
A website search form may submit fields like:
- keyword
- category
- page number
Your PHP script can mimic that form submission and retrieve the results page.
Logging into a website
Some pages only show content after a login form is submitted with POST.
Calling APIs
Many APIs expect POST when you:
- create a new record
- submit filters too large for a URL
- send JSON payloads
- send authentication data
Web scraping after form submission
If a site generates results only after submitting a search form, you must send the correct POST fields before parsing the returned HTML.
Internal backend communication
A PHP application might send POST requests to another service to:
- validate payments
- submit orders
- trigger notifications
- fetch report results based on filters
Real Codebase Usage
In real projects, developers usually prefer cURL because it supports more features and better error handling.
Common patterns
Guard clauses for failed requests
<?php
$response = curl_exec($ch);
if ($response === false) {
throw new Exception(curl_error($ch));
}
This avoids continuing with invalid data.
Checking HTTP status codes
<?php
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($statusCode !== 200) {
throw new Exception('Unexpected status code: ' . $statusCode);
}
A request can succeed technically but still return an error page like 404 or 500.
Reusable helper functions
Teams often wrap POST requests in utility functions.
Common Mistakes
1. Using file_get_contents() without a POST context
Broken example:
<?php
$response = file_get_contents('https://example.com/search');
Problem:
- This sends a GET request by default.
- It will not work correctly if the server requires POST.
Fix:
- Use a stream context with method
POST, or use cURL.
2. Forgetting CURLOPT_RETURNTRANSFER
Broken example:
<?php
$ch = curl_init('https://example.com/search');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'query=php');
$response = curl_exec($ch);
Problem:
- Without
CURLOPT_RETURNTRANSFER, the response may be output directly.
Comparisons
| Approach | Best for | Strengths | Limitations |
|---|---|---|---|
cURL | Most HTTP requests in PHP | Flexible, supports headers, cookies, auth, status codes, redirects | Slightly more code |
file_get_contents() with stream context | Simple POST requests | Built in, easy for small tasks | Less control and weaker error handling |
DOMDocument | Parsing returned HTML | Good for extracting elements from HTML | Does not send HTTP requests by itself |
POST vs GET
| Method | Data location |
|---|
Cheat Sheet
// cURL POST request
$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);
curl_close($ch);
// file_get_contents() POST request
$options = [
'http' => [
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Key rules
FAQ
Can PHP send a POST request without cURL?
Yes. You can use file_get_contents() with a stream context that sets the method to POST and includes the request body.
Is cURL better than file_get_contents() for POST requests?
Usually yes. cURL provides better control over headers, cookies, redirects, status codes, and error handling.
How do I send form fields in a PHP POST request?
Put the fields in an associative array and use http_build_query($data) to convert them into form-encoded data.
How do I read the response after sending a POST request in PHP?
Store the returned value from curl_exec() or file_get_contents() in a variable, then print it or parse it.
Can I parse the returned HTML with DOMDocument?
Yes. First send the POST request and store the response body, then pass that HTML string to DOMDocument::loadHTML().
What if the server expects JSON instead of form data?
Use json_encode($data) for the body and send the header Content-Type: application/json.
Why is my POST request returning nothing?
Common reasons include missing headers, wrong parameter names, no , request errors, or the server requiring authentication or cookies.
Mini Project
Description
Build a small PHP script that submits a search term to a POST-only endpoint and prints the returned content. This demonstrates the full workflow: preparing form data, sending a POST request, receiving the response, and optionally parsing it.
Goal
Create a reusable PHP function that sends POST data to a URL and returns the response body.
Requirements
- Accept a target URL and an array of POST fields.
- Send the request using the POST method.
- Return the response body as a string.
- Handle request errors safely.
- Demonstrate the function with a sample call.
Keep learning
Related questions
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.
Convert a PHP Object to an Associative Array
Learn how to convert a PHP object to an associative array, including quick methods, recursion, pitfalls, and practical examples.
Convert a Postman Request to cURL and PHP cURL
Learn how to convert a Postman POST request into a cURL command and use the same request in PHP cURL with headers and body.