POST data to a URL in PHP

POST data to a URL in PHP

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Understanding HTTP POST in PHP Without a Form

Sending data to a remote endpoint without an HTML form is a common requirement in server-to-server communication, such as webhook integrations or API calls from scripts. In these scenarios, you need to manually construct the request payload and set the appropriate headers to mimic the behavior of a standard browser submission. The core mechanism relies on PHP's file_get_contents() function when paired with specific options, or more robustly, using cURL.

The most straightforward approach for simple payloads involves file_get_contents(). You can pass an associative array of data to this function; PHP will automatically serialize it into a URL-encoded string and set the necessary headers. Consider a scenario where you have a variable containing user data that needs to be submitted to a third-party service:

$data = [
    'email' => 'user@example.com',
    'status' => 'active',
    'token' => 'xyz123abc'
];

$url = 'https://api.example.com/submit';

$response = file_get_contents($url, true, stream_context_create([
    'http' => [
        'method'  => 'POST',
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query($data)
    ]
]));

if ($response !== false) {
    echo "Success: " . $response;
} else {
    echo "Failed.";
}

In this example, http_build_query() converts the array into a string formatted as email=user%40example.com&status=active&token=xyz123abc. This matches the default behavior of an HTML form submission. The stream_context_create function allows you to inject these parameters directly into the underlying HTTP stream without needing to open a full socket connection manually.

However, relying solely on file_get_contents() can be problematic in production environments due to limitations with SSL verification and error handling. If the remote server uses HTTPS, PHP might skip certificate validation by default, which creates a security risk. You should explicitly configure the context to verify SSL certificates unless there is a specific reason not to:

$context = stream_context_create([
    'ssl' => [
        'verify_peer' => true,
        'verify_peer_name' => true
    ]
]);

For more complex interactions—such as sending JSON payloads or handling large file uploads—cURL is the preferred tool. It offers granular control over headers, timeouts, and redirect handling. To send the same data using cURL, you would initialize a handle, set the method to POST, and attach the serialized data:

$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); // Return response instead of outputting directly
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode === 200) {
    echo "Success: " . $response;
} else {
    echo "Request failed with HTTP code {$httpCode}.";
}

One critical detail often overlooked is the Content-Type header. While file_get_contents() defaults to application/x-www-form-urlencoded, many modern APIs expect application/json. If you switch to JSON, you must serialize the data using json_encode() and update the header accordingly. Failing to match the expected content type on the receiving end will result in a 400 Bad Request error, regardless of whether the data is valid.

When implementing these solutions, always handle exceptions or errors gracefully. Network timeouts, DNS failures, or remote server rejections can occur at any time. Checking the return value and HTTP status code ensures your script fails safely rather than silently ignoring the failure. If you are building this functionality within a Laravel application, consider using the Http facade or service providers to abstract these details into reusable classes, ensuring consistent error handling across your stack.

Our network