php CURLOPT_POSTFIELDS 的 curl POST 格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5224790/
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 20:40:37  来源:igfitidea点击:

curl POST format for CURLOPT_POSTFIELDS

phppostcurl

提问by Ken

When I use curlvia POSTand set CURLOPT_POSTFIELDdo I have to urlencodeor any special format?

当我使用curlviaPOST和 set 时CURLOPT_POSTFIELD,我必须使用urlencode或任何特殊格式吗?

for example: If I want to post 2 fields, first and last:

例如:如果我想发布 2 个字段,第一个和最后一个:

first=John&last=Smith

what is the exact code/format that should be used with curl?

应该与 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);

回答by kodeart

In case you are sending a string, urlencode() it. Otherwise if array, it should be key=>value paired and the Content-typeheader is automatically set to multipart/form-data.

如果您要发送字符串,请使用 urlencode()。否则,如果是数组,它应该是 key=>value 配对,并且Content-type标头自动设置为multipart/form-data

Also, you don't have to create extra functions to build the query for your arrays, you already have that:

此外,您不必创建额外的函数来为您的数组构建查询,您已经拥有了:

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

回答by Czechnology

EDIT: From php5 upwards, usage of http_build_queryis recommended:

编辑:从 php5 起,http_build_query推荐使用:

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

Simple example from the manual:

手册中的简单示例:

<?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
*/

?>


before php5:

在 php5 之前:

From the manual:

手册

CURLOPT_POSTFIELDS

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. The filetype can be explicitly specified by following the filename with the type in the format ';type=mimetype'. This parameter 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. If value is an array, the Content-Type header will be set to multipart/form-data.As of PHP 5.2.0, files thats passed to this option with the @ prefix must be in array form to work.

CURLOPT_POSTFIELDS

要在 HTTP“POST”操作中发布的完整数据。要发布文件,请在文件名前加上 @ 并使用完整路径。文件类型可以通过在文件名后面加上“;type=mimetype”格式的类型来明确指定。此参数可以作为 urlencoded 字符串(如 'para1=val1¶2=val2&...')或作为以字段名称作为键和字段数据作为值的数组传递。如果 value 是一个数组,则 Content-Type 标头将设置为 multipart/form-data。从 PHP 5.2.0 开始,传递给此选项的带有 @ 前缀的文件必须采用数组形式才能工作。

So something like this should work perfectly (with parameters passed in a associative array):

所以这样的事情应该完美地工作(在关联数组中传递参数):

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

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

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

回答by ThiefMaster

Do not pass a string at all!

根本不要传递字符串!

You can pass an array and let php/curl do the dirty work of encoding etc.

你可以传递一个数组,让 php/curl 做编码等肮脏的工作。

回答by Surreal Dreams

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.

根据 PHP 手册,作为字符串传递给 cURL 的数据应该进行 URLencoded。请参阅curl_setopt()页面并搜索CURLOPT_POSTFIELDS.

回答by Shraddha Vadnere

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

对于CURLOPT_POSTFIELDS,参数既可以作为 urlencoded 字符串传递,也可以作为para1=val1&para2=val2&..数组传递,字段名称作为键,字段数据作为值

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

回答by 7ochem

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

此处尚未提及的另一个主要区别是CURLOPT_POSTFIELDS无法处理嵌套数组。

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).

如果我们采用嵌套数组,['a' => 1, 'b' => [2, 3, 4]]那么这应该被参数化为a=1&b[]=2&b[]=3&b[]=4[并且]将/应该是 URL 编码的)。这将自动转换回另一端的嵌套数组(假设这里的另一端也是 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 bas string "Array":

这会给你一个通知。代码执行将继续,您的端点将接收b字符串形式的参数"Array"

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

PHP 注意:数组到字符串的转换 in ... 在线 ...

回答by Buzut

It depends on the content-type

这取决于 content-type

url-encoded or multipart/form-data

url-encoded 或 multipart/form-data

To send data the standard way, as a browser would with a form, just pass an associative array. As stated by PHP's manual:

要以标准方式发送数据,就像浏览器发送表单一样,只需传递一个关联数组。正如 PHP 手册所述:

This parameter 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. If value is an array, the Content-Type header will be set to multipart/form-data.

此参数可以作为 urlencoded 字符串(如 'para1=val1¶2=val2&...')或作为以字段名称作为键和字段数据作为值的数组传递。如果 value 是一个数组,则 Content-Type 标头将设置为 multipart/form-data。

JSON encoding

JSON 编码

Neverthless, when communicating with JSON APIs, content must be JSON encoded for the API to understand our POST data.

尽管如此,在与 JSON API 通信时,内容必须是 JSON 编码的 API 才能理解我们的 POST 数据。

In such cases, content must be explicitely encoded as JSON :

在这种情况下,内容必须明确编码为 JSON :

CURLOPT_POSTFIELDS => json_encode(['param1' => $param1, 'param2' => $param2]),

When communicating in JSON, we also usually set acceptand content-typeheaders accordingly:

在 JSON 中进行通信时,我们通常也会相应地设置acceptcontent-type标头:

CURLOPT_HTTPHEADER => [
    'accept: application/json',
    'content-type: application/json'
]

回答by Maxim Rysevets

for nested arrays you can use:

对于嵌套数组,您可以使用:

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

回答by Klompenrunner

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

有趣的是,Postman执行 POST的方式是一个完整的 GET 操作,带有这两个附加选项:

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

Just another way, and it works very well.

只是另一种方式,而且效果很好。

回答by user2512571

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:

这个答案也花了我很长时间才找到。我发现您所要做的就是将 URL(文件名和扩展名后的“?”)与 URL 编码的查询字符串连接起来。看起来您甚至不必设置 POST cURL 选项。请参阅下面的假示例:

//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():

您还可以使用file_get_contents()

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