【问题标题】:How to post same names for file and parameter name by php curl CURLOPT_POSTFIELDS?如何通过 php curl CURLOPT_POSTFIELDS 为文件和参数名称发布相同的名称?
【发布时间】:2017-12-10 23:45:35
【问题描述】:

我通过 curl 命令将文件和参数发布到 t.php:

t.php:

<?php

print_r( $_FILES );
print_r( $_POST );
?>

文件和参数“name”需要相同的名称:

curl http://localhost/t.php -X POST -F "name=@D:\file.zip" -F "name=test"

结果是:

Array
(
    [name] => Array
        (
            [name] => file.zip
            [type] => application/octet-stream
            [tmp_name] => D:\www\tmp\php653B.tmp
            [error] => 0
            [size] => 150
        )

)
Array
(
    [name] => test
)

没关系!

但是, 如何通过 php curl CURLOPT_POSTFIELDS 为文件和参数名称发布相同的名称?

//
$data = [
    'name' => curl_file_create('D:\file.zip'),
    //'name' => 'test', // <--- ?????????????
];

$curl = curl_init('http://localhost/t.php');
curl_setopt($curl, CURLOPT_POST, 1); 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data );
$out = curl_exec($curl);
curl_close($curl);

请帮帮我

【问题讨论】:

    标签: php curl post


    【解决方案1】:

    准备数据数组,如下所示:

    $data = array('name' => 'Foo', 'file' => '@/home/user/test.png');
    

    注意:@ 附加在文件路径之前。

    以下示例取自 php.net。

    <?php
    
    $ch = curl_init();
    
    $data = array('name' => 'Foo', 'file' => '@/home/user/test.png');
    
    curl_setopt($ch, CURLOPT_URL, 'http://localhost/upload.php');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    
    curl_exec($ch);
    ?>
    

    【讨论】:

      【解决方案2】:
      $boundary = '---'.time().'---' ;
      $header = 'Content-Type: multipart/form-data; boundary='.$boundary;
      
      $filename = 'D:\file.zip';
      $file_contents = file_get_contents($filename);
      $content =  "--". $boundary . "\r\n".
                  "Content-Disposition: form-data; name=\"name\"; filename=\"".basename($filename)."\"\r\n".
                  "Content-Type: application/zip\r\n\r\n".
                  $file_contents."\r\n";
      $content .= "--". $boundary. "\r\n".
                  "Content-Disposition: form-data; name=\"name\"\r\n\r\n".
                  "test\r\n";
      $content .= "--" . $boundary . "--\r\n";
      $context = stream_context_create(array(
          'http' => array(
                'method' => 'POST',
                'header' => $header,
                'content' => $content,
          )
      ));
      $result = file_get_contents('http://localhost/t.php', false, $context);
      

      【讨论】:

        猜你喜欢
        • 2020-11-27
        • 2015-11-10
        • 2015-03-26
        • 1970-01-01
        • 1970-01-01
        • 2016-06-30
        • 2012-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多