Table of contents

application-x-www-form-urlencoded post in php cURL

PHP cURL Jun 01, 2020 Viewed 1K Comments 0

With application-x-www-form-urlencoded post in cURL, we should use http_build_query to generate URL-encode data and put them in CURLOPT_POSTFIELDS.

Example

function post($url, $data, $headers)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true, // return the transfer as a string of the return value
        CURLOPT_TIMEOUT => 0,   // The maximum number of seconds to allow cURL functions to execute.
        CURLOPT_POST => true,   // This line must place before CURLOPT_POSTFIELDS
        CURLOPT_POSTFIELDS => $data // Data that will send
    ));
    // Set Header
    if (!empty($headers)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    }
    $response = curl_exec($curl);
    $errno = curl_errno($curl);
    if ($errno) {
        return false;
    }
    curl_close($curl);
    return $response;
}

Use it

The following is an example of sending an array.

$arr = [
    "name" => "test",
    "password" => "mypasswd",
    "arr[0]" => 0,
    "arr[1]" => 1,
];
$data = http_build_query($arr);
$headers = ["User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"];
echo post("http://localhost/response.php", $data, $headers);

response.php

print_r($_REQUEST);
$contentType = $_SERVER["CONTENT_TYPE"];
print_r($contentType);

Output

Array
(
    [name] => test
    [password] => mypasswd
    [arr] => Array
        (
            [0] => 0
            [1] => 1
        )

)
application/x-www-form-urlencoded

The request header Content-ype is automatically set to application/x-www-form-urlencoded.

Updated Jun 01, 2020