Question

How to Send a POST Request with PHP and Read the Response

phphttppostrequest

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:

  1. build the POST data
  2. send the request using a PHP HTTP client mechanism
  3. capture the response body
  4. 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.

Take Quiz

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
  • CURLOPT_POST tells cURL to use POST
  • CURLOPT_POSTFIELDS sends the form data
  • http_build_query($data) converts the array into standard form data like query=php&category=books
  • CURLOPT_RETURNTRANSFER returns the response as a string instead of printing it immediately

Using file_get_contents() with a POST context

If you want a simpler built-in approach, you can use a stream context.

<?php
$url = 'https://example.com/search';
$data = [
    'query' => 'php',
    'category' => 'books'
];

$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);

echo $response;

What this does

  • creates a custom HTTP request context
  • sets the request method to POST
  • sets the content type for normal form submission
  • sends the encoded POST body
  • reads the returned response body

Parsing returned HTML with DOMDocument

Once you have the response HTML, you can parse it.

<?php
libxml_use_internal_errors(true);

$dom = new DOMDocument();
$dom->loadHTML($response);

$paragraphs = $dom->getElementsByTagName('p');

foreach ($paragraphs as $p) {
    echo $p->textContent . PHP_EOL;
}

This is useful when the POST request returns an HTML page and you want to extract data from it.

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

  1. Create the target URL

    • $url stores the address you want to send the request to.
  2. Prepare the POST data

    • $data is an associative array.
    • It contains one field: query=laptop.
  3. Start a cURL session

    • curl_init($url) prepares a request for that URL.
  4. Set the request to POST

    • CURLOPT_POST changes the request method from the default GET to POST.
  5. Attach the POST body

    • CURLOPT_POSTFIELDS sends the encoded form data.
    • http_build_query($data) turns the array into a valid request body.
  6. Capture the response as a string

    • CURLOPT_RETURNTRANSFER prevents automatic output.
    • Instead, the response is stored in $response.
  7. Execute the request

    • curl_exec($ch) sends the POST request to the server.
    • The server processes the submitted data and returns content.
  8. Close the connection

    • curl_close($ch) frees resources.
  9. Use the response

    • echo $response prints the returned page content.
    • You could also pass $response to DOMDocument or decode JSON if needed.

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
Take Quiz

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.

<?php
function postRequest(string $url, array $data): string
{
    $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) {
        $error = curl_error($ch);
        curl_close($ch);
        throw new Exception($error);
    }

    curl_close($ch);
    return $response;
}

Sending JSON instead of form data

Some APIs expect JSON rather than application/x-www-form-urlencoded.

<?php
$url = 'https://api.example.com/items';
$data = [
    'name' => 'Book',
    'price' => 20
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json'
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
curl_close($ch);

The request format must match what the server expects.

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.
  • $response may be true instead of the response body.

Fix:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

3. Sending an array in the wrong format

Broken example:

<?php
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

Problem:

  • Sometimes this works, but the request format may differ from what the server expects.
  • If the server expects regular form fields, encode them clearly.

Fix:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

4. Forgetting required headers

If the server expects JSON and you send form data, the request may fail.

Fix:

  • Use the correct Content-Type
  • Match the server's expected format exactly

5. Ignoring errors

Broken example:

<?php
$response = curl_exec($ch);
curl_close($ch);
echo $response;

Problem:

  • If the request fails, you may not know why.

Fix:

<?php
$response = curl_exec($ch);
if ($response === false) {
    echo curl_error($ch);
}

6. Assuming returned content is always HTML

Some endpoints return JSON, XML, or plain text.

Fix:

  • inspect the response
  • check headers if needed
  • parse based on actual format

Comparisons

ApproachBest forStrengthsLimitations
cURLMost HTTP requests in PHPFlexible, supports headers, cookies, auth, status codes, redirectsSlightly more code
file_get_contents() with stream contextSimple POST requestsBuilt in, easy for small tasksLess control and weaker error handling
DOMDocumentParsing returned HTMLGood for extracting elements from HTMLDoes not send HTTP requests by itself

POST vs GET

MethodData locationTypical useNotes
GETURL query stringReading data, simple filtersVisible in URL, length limits may apply
POSTRequest bodyForm submission, creating resources, larger payloadsNot shown in URL, commonly used for forms and APIs

Form data vs JSON

FormatContent-TypeTypical use
application/x-www-form-urlencodedStandard form postsHTML forms and many older endpoints
application/jsonJSON APIsModern APIs and backend services
Take Quiz

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

  • file_get_contents() uses GET unless you provide a stream context.
  • cURL is the preferred option for real projects.
  • Use http_build_query() for regular form-style POST data.
  • Use json_encode() and Content-Type: application/json for JSON APIs.
  • Set CURLOPT_RETURNTRANSFER if you want the response as a string.
  • Check for errors with curl_error() and response codes with curl_getinfo().

Useful follow-up parsing

// Parse JSON
$data = json_decode($response, true);
// Parse HTML
$dom = new DOMDocument();
$dom->loadHTML($response);

Common edge cases

  • Server requires cookies or sessions
  • Server redirects after POST
  • Server blocks missing headers
  • Response is compressed, JSON, or malformed HTML

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 CURLOPT_RETURNTRANSFER, request errors, or the server requiring authentication or cookies.

Take Quiz

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

  1. Accept a target URL and an array of POST fields.
  2. Send the request using the POST method.
  3. Return the response body as a string.
  4. Handle request errors safely.
  5. Demonstrate the function with a sample call.
Take Quiz

Keep learning

Related questions

View more