Raw POST using cURL in PHP

PHP cURL May 14, 2020 Viewed 4.8K Comments 0

We can do a raw POST with cURL library, which can send text data to server, such as json, xml, html and so on. Just convert data to string, and put in curl_setopt($curl, CURLOPT_POSTFIELDS, $data)

Example

function post($url, $data, $headers)
{
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => $data,
    ));
    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;
}

Submit JSON data

Use it.

$arr = [
    "name" => "test",
    "password" => "123456",
];
$data = json_encode($arr, JSON_UNESCAPED_SLASHES);
$headers = ["Content-Type: application/json"];
echo post("http://localhost/response.php", $data, $headers);

reponse.php

$raw = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : null;
$data = json_decode($raw, JSON_OBJECT_AS_ARRAY);
print_r($data);

Output

Array
(
    [name] => test
    [password] => 123456
)

Submit XML data

Use it.

$data = <<<EOD
<xml>
<attach>weixin</attach>
<bank_type>ICBC_DEBIT</bank_type>
<cash_fee>2530</cash_fee>
<fee_type>CNY</fee_type>
<is_subscribe>N</is_subscribe>
<return_code>SUCCESS</return_code>
<total_fee>2530</total_fee>
</xml>
EOD;
$headers = ["Content-Type: application/xml"];
echo post("http://localhost/response.php", $data, $headers);

reponse.php

$raw = isset($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : null;
$arr = simplexml_load_string($raw, 'SimpleXMLElement', LIBXML_NOCDATA);
print_r($arr);

Output

SimpleXMLElement Object
(
    [attach] => weixin
    [bank_type] => ICBC_DEBIT
    [cash_fee] => 2530
    [fee_type] => CNY
    [is_subscribe] => N
    [return_code] => SUCCESS
    [total_fee] => 2530
)
Updated May 14, 2020