在PHP中使用cURL的RAW POST

The*_*own 114 php post curl put

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

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

... 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
Run Code Online (Sandbox Code Playgroud)

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

无论如何,我可以只将选项传递给curl_setopt(),说使用POST,使用text/plain,并从一个$variable?发送原始数据?

The*_*own 208

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

$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);
Run Code Online (Sandbox Code Playgroud)

  • 我刚刚意识到**身体在这里**可以包含任何有效的json字符串. (10认同)
  • php会为你设置内容长度标题还是你也应该设置它? (4认同)
  • 我根本无法工作.我有一个页面,我试图发布原始数据.该页面将收到的所有原始数据记录到数据库表中.根本没有新的行.你知道自09年以来有什么变化吗? (3认同)
  • 此原始帖子有 2G 限制。如果您尝试发送大于 2G 的文件,它们将被截断回 2G。它是加载的字符串类型的限制。 (2认同)

Ser*_*huk 7

使用 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()
);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

源代码