在 PHP 中使用 cURL 的 RAW POST

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/871431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:10:12  来源:igfitidea点击:

RAW POST using cURL in PHP

phppostcurlput

提问by The Unknown

How can I do a RAW POST in PHP using cURL?

如何使用 cURL 在 PHP 中执行 RAW POST?

Raw post as in without any encoding, and my data is stored in a string. The data should be formatted like this:

原始帖子没有任何编码,我的数据存储在一个字符串中。数据格式应如下所示:

... usual HTTP header ...
Content-Length: 1039
Content-Type: text/plain

89c5fdataasdhf kajshfd akjshfksa hfdkjsa falkjshfsa
ajshd fkjsahfd lkjsahflksahfdlkashfhsadkjfsalhfd
ajshdfhsafiahfiuwhflsf this is just data from a string
more data kjahfdhsakjfhsalkjfdhalksfd

One option is to manually write the entire HTTP header being sent, but that seems less optimal.

一种选择是手动编写正在发送的整个 HTTP 标头,但这似乎不太理想。

Anyway, can I just pass options to curl_setopt() that say use POST, use text/plain, and send the raw data from a $variable?

无论如何,我可以将选项传递给 curl_setopt() 说使用 POST、使用文本/纯文本并从$variable.

回答by The Unknown

I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.

我刚刚找到了解决方案,有点回答我自己的问题,以防其他人偶然发现它。

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,            "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST,           1 );
curl_setopt($ch, CURLOPT_POSTFIELDS,     "body goes here" ); 
curl_setopt($ch, CURLOPT_HTTPHEADER,     array('Content-Type: text/plain')); 

$result=curl_exec ($ch);

回答by Serhii Andriichuk

Implementation with Guzzle library:

使用 Guzzle 库实现:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

PHP CURL 扩展:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

源代码