programing

PHP의 cURL을 사용한 RAW POST

itsource 2022. 9. 28. 23:39
반응형

PHP의 cURL을 사용한 RAW POST

cURL을 사용하여 PHP에서 RAW POST를 하려면 어떻게 해야 하나요?

인코딩 없이 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

송신되는 HTTP 헤더 전체를 수동으로 쓰는 방법도 있습니다만, 최적이 아닌 것 같습니다.

어쨌든, curl_setopt()에 POST 사용, 텍스트/플레인 사용, raw data 전송 등의 옵션을 전달해도 될까요?$variable?

다른 사람이 실수할 경우를 대비해서 내 질문에 답을 해줬지

$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);

Guzle 라이브러리를 사용한 구현:

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 확장:

$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);

소스 코드

언급URL : https://stackoverflow.com/questions/871431/raw-post-using-curl-in-php

반응형