program story

CURLOPT_POSTFIELDS에 대한 curl POST 형식

inputbox 2020. 8. 25. 07:57
반응형

CURLOPT_POSTFIELDS에 대한 curl POST 형식


내가 사용하는 경우 curl를 통해 POST와 세트 CURLOPT_POSTFIELD할 나는에있는 urlencode또는 특별한 형식?

예 : 첫 번째와 마지막 두 개의 필드를 게시하려는 경우 :

first=John&last=Smith

curl과 함께 사용해야하는 정확한 코드 / 형식은 무엇입니까?

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$reply=curl_exec($ch);
curl_close($ch);

문자열을 보내는 경우 urlencode () 그것. 그렇지 않으면 배열 인 경우 key => value 쌍이어야하며 Content-type헤더는 자동으로로 설정됩니다 multipart/form-data.

또한 배열에 대한 쿼리를 작성하기 위해 추가 함수를 만들 필요가 없습니다. 이미 다음이 있습니다.

$query = http_build_query($data, '', '&');

편집 : php5 이상에서 다음을 사용하는 http_build_query것이 좋습니다.

string http_build_query ( mixed $query_data [, string $numeric_prefix [, 
                          string $arg_separator [, int $enc_type = PHP_QUERY_RFC1738 ]]] )

매뉴얼의 간단한 예 :

<?php
$data = array('foo'=>'bar',
              'baz'=>'boom',
              'cow'=>'milk',
              'php'=>'hypertext processor');

echo http_build_query($data) . "\n";

/* output:
foo=bar&baz=boom&cow=milk&php=hypertext+processor
*/

?>

php5 이전 :

로부터 수동 :

CURLOPT_POSTFIELDS

HTTP "POST"작업에 게시 할 전체 데이터입니다. 파일을 게시하려면 파일 이름 앞에 @를 추가하고 전체 경로를 사용하십시오. 파일 유형은 '; type = mimetype'형식의 유형과 함께 파일 이름을 따라 명시 적으로 지정할 수 있습니다. 이 매개 변수는 'para1 = val1 & para2 = val2 & ...'와 같은 urlencoded 문자열로 전달되거나 필드 이름이 키로, 필드 데이터가 값으로 포함 된 배열로 전달 될 수 있습니다. 값이 배열이면 Content-Type 헤더가 multipart / form-data로 설정됩니다. PHP 5.2.0부터 @ 접두사를 사용하여이 옵션에 전달 된 파일이 작동하려면 배열 형식이어야합니다.

따라서 다음과 같은 것이 완벽하게 작동합니다 (연관 배열로 전달 된 매개 변수 사용).

function preparePostFields($array) {
  $params = array();

  foreach ($array as $key => $value) {
    $params[] = $key . '=' . urlencode($value);
  }

  return implode('&', $params);
}

문자열을 전혀 전달하지 마십시오!

배열을 전달하고 php / curl이 인코딩 등의 더러운 작업을 수행하도록 할 수 있습니다.


According to the PHP manual, data passed to cURL as a string should be URLencoded. See the page for curl_setopt() and search for CURLOPT_POSTFIELDS.


One other major difference that is not yet mentioned here is that CURLOPT_POSTFIELDS can't handle nested arrays.

If we take the nested array ['a' => 1, 'b' => [2, 3, 4]] then this should be be parameterized as a=1&b[]=2&b[]=3&b[]=4 (the [ and ] will be/should be URL encoded). This will be converted back automatically into a nested array on the other end (assuming here the other end is also PHP).

This will work:

var_dump(http_build_query(['a' => 1, 'b' => [2, 3, 4]]));
// output: string(36) "a=1&b%5B0%5D=2&b%5B1%5D=3&b%5B2%5D=4"

This won't work:

curl_setopt($ch, CURLOPT_POSTFIELDS, ['a' => 1, 'b' => [2, 3, 4]]);

This will give you a notice. Code execution will continue and your endpoint will receive parameter b as string "Array":

PHP Notice: Array to string conversion in ... on line ...


for nested arrays you can use:

$data = [
  'name[0]' = 'value 1',
  'name[1]' = 'value 2',
  'name[2]' = 'value 3',
  'id' = 'value 4',
  ....
];

For CURLOPT_POSTFIELDS, the parameters can either be passed as a urlencoded string like para1=val1&para2=val2&.. or as an array with the field name as key and field data as value

Try the following format :

$data = json_encode(array(
"first"  => "John",
"last" => "Smith"
));

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);

Interestingly the way Postman does POST is a complete GET operation with these 2 additional options:

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, '');

Just another way, and it works very well.


This answer took me forever to find as well. I discovered that all you have to do is concatenate the URL ('?' after the file name and extension) with the URL-encoded query string. It doesn't even look like you have to set the POST cURL options. See the fake example below:

//create URL
$exampleURL = 'http://www.example.com/example.php?';

// create curl resource
$ch = curl_init(); 

// build URL-encoded query string
$data = http_build_query(
    array('first' => 'John', 'last' => 'Smith', '&'); // set url
curl_setopt($ch, CURLOPT_URL, $exampleURL . $data); 

// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

// $output contains the output string
$output = curl_exec($ch); 

// close curl resource to free up system resources <br/>
curl_close($ch);

You can also use file_get_contents():

// read entire webpage file into a string
$output = file_get_contents($exampleURL . $data);

참고URL : https://stackoverflow.com/questions/5224790/curl-post-format-for-curlopt-postfields

반응형