[英]How to post same names for file and parameter name by php curl CURLOPT_POSTFIELDS?
我通過curl命令將文件和參數發布到t.php:
t.php:
<?php
print_r( $_FILES );
print_r( $_POST );
?>
文件和參數“名稱”需要相同的名稱:
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);
請幫幫我
$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);
准備數據數組,如下所示:
$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);
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.