Sending POST Requests in PHP: Handling Form Data and Reading Responses
When a server endpoint restricts access to the POST method and explicitly rejects GET requests, you cannot simply append query parameters to the URL. Attempting to fetch such a resource with file_get_contents() while passing data as GET arguments will result in a 405 Method Not Allowed error or a silent failure if the server ignores the request body for GET calls. To interact with these APIs, you must construct a request that mimics a form submission or a JSON payload, ensuring the HTTP verb is POST and the data is included in the request stream.
The most straightforward approach in native PHP involves using file_get_contents() combined with http_build_query(). This method allows you to send associative arrays as URL-encoded form fields. However, this technique has significant limitations regarding content type detection and advanced headers. If your target API expects JSON rather than application/x-www-form-urlencoded data, sending a simple query string will likely fail validation on the server side.
$url = 'https://example.com/api/search';
// Prepare form data
$data = [
'q' => 'search term',
'page' => 1
];
// Build the query string
$query_string = http_build_query($data);
// Execute the request
$response = file_get_contents($url . '?' . $query_string);
if ($response) {
// Parse the result, potentially using DOMDocument for HTML/XML
$dom = new DOMDocument();
@libxml_use_internal_errors(true);
$dom->loadHTML($response);
} else {
// Handle errors; file_get_contents returns false on failure
// Check stream_context options if curl is not used
}
While the code above demonstrates sending data, relying solely on file_get_contents() for complex POST requests often requires setting up a custom stream_context. You must explicitly define that the request method is POST and specify the Content-Type. Without these context options, PHP defaults to a GET-like behavior even if you pass arguments, which defeats the purpose of the server's restriction.
$context = stream_context_create([
'http' => [
'method' => 'POST',
'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($data)
]
]);
$response = file_get_contents($url, false, $context);
For projects involving more complex headers or binary data, the cURL extension is generally preferred. It provides granular control over request bodies, timeouts, and SSL verification. With cURL, you can easily switch between application/x-www-form-urlencoded and application/json by altering the CURLOPT_HTTPHEADER option. This flexibility makes it the standard choice for production environments where strict adherence to API specifications is required.
If you are working within the Laravel ecosystem, handling this interaction becomes even more streamlined. The framework's HTTP client, accessible via the Http facade or dependency injection, abstracts away the underlying stream context or cURL configuration. You can define a custom service that handles these specific POST-only endpoints, injecting it into your controllers to ensure consistent request formatting and automatic error handling for non-2xx status codes.
use Illuminate\Support\Facades\Http;
$response = Http::post('https://example.com/api/search', [
'q' => 'search term',
'page' => 1
])->throw(); // Throw an exception on HTTP errors
$contents = $response->body();
$dom = new DOMDocument();
@libxml_use_internal_errors(true);
$dom->loadHTML($contents);
The primary trade-off when choosing between native streams and frameworks is dependency and abstraction. Native PHP offers zero overhead but requires manual error checking and context management. Frameworks like Laravel provide robust exception handling and middleware support, which is invaluable when integrating with external services that enforce strict protocols. However, always remember to verify the Content-Type expected by the remote server; sending JSON data as form fields or vice versa is a common source of silent failures in API integrations.
