Send/Post Form Data to Url with PHP

Send/Post Form Data to Url with PHP

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

Stefan Bogdanescu

Founder & Senior Architect

Sending Form Data to a Third-Party API with PHP

Capturing form inputs is standard practice, but forwarding that data to another service—like an external API or a logging endpoint—is where things often get tricky. The core challenge involves securely constructing a request body, handling URL encoding, and managing the HTTP lifecycle without exposing sensitive information or breaking your application flow.

Why the Simple String Concatenation Approach Fails

A common initial attempt might look like this:

$url = 'https://api.this.com/foo/bar?token=IHAVETOKEN&foo=' . $var1 . '&bar=' . $var2;
// Then manually POSTing to that URL

While conceptually simple, this approach has significant flaws. First, it requires manual URL encoding. If $var1 or $var2 contains spaces, ampersands, or special characters like & or =, the resulting query string will break unless you use urlencode(). Second, manually parsing the form into a query string assumes the receiving API accepts GET parameters for POST requests, which is often not the case. Many APIs expect a JSON body or a specific format in the request payload rather than appended query parameters.

The most robust method involves using the cURL extension to handle the request construction and transmission automatically. This ensures proper escaping, correct header handling, and reliable execution.

Constructing the Request Body

In your PHP logic, you should first gather the data from $_POST or $_GET. Once collected, organize it into an associative array. This structure mirrors the keys expected by the receiving endpoint.

$data = [
    'token' => 'IHAVETOKEN',
    'firstName' => $_POST['firstname'],
    'lastName' => $_POST['lastname'],
    'email' => $_POST['email'],
    'password' => $_POST['password'], // Be careful with passwords in logs
    'phone' => $_POST['phone']
];

Next, convert this array into a URL-encoded string. The http_build_query function is perfect for this task. It handles the escaping of special characters and formats the data as key=value&key2=value2. Note that you should append a newline character (\n) or ensure the content-type header matches what the API expects, though cURL often handles this implicitly if configured correctly.

$postvars = http_build_query($data);

Executing the Request with cURL

With the data prepared, initialize a cURL session. This allows you to set specific options that prevent you from having to manually write an HTTP request line.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://api.com/foo/bar');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Returns response instead of outputting directly

It is crucial to set CURLOPT_RETURNTRANSFER to true if you intend to inspect the $server_output. This lets you verify that the external API responded successfully (e.g., checking for a 200 OK status) before deciding whether to proceed with the redirect.

If your API requires JSON instead of URL-encoded data, you would change CURLOPT_POSTFIELDS to be a serialized JSON string and set the appropriate headers:

curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);

Handling the Response and Redirecting

After executing the request with curl_exec, always check if the response indicates success. If an error occurred during the POST, redirecting the user immediately to a "Thank You" page could mask the issue or lead to a poor user experience where data was supposedly sent but wasn't.

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

if ($server_output) {
    header('Location: thankyou.php');
} else {
    // Handle error, log $server_output for debugging
    die('Failed to send data to external API.');
}

Security Considerations

When dealing with form data that includes passwords or sensitive tokens, ensure you are not inadvertently logging these values. Always verify the destination URL is secure (HTTPS) and validate the token parameter strictly if it acts as an authentication mechanism.

For projects built on top of Laravel, you might find similar patterns in packages like LaravelCompany's utilities, which often abstract away low-level cURL calls to simplify API interactions within a framework context. However, understanding the underlying mechanics remains essential for debugging and performance optimization.

By using http_build_query combined with cURL options, you ensure that your form data is transmitted accurately and securely, regardless of the characters involved in the input fields.

Our network