[英]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.