繁体   English   中英

使用PHP上传多个文件

[英]Upload multiple files with PHP

我正在尝试使用此代码通过PHP 5.5上传多个文件并附加到电子邮件中。 如果我在input字段的name属性上从file[] (所以是file )中得到括号,则可以成功上传一个文件; 如果我放回括号,该页面会发出此警告(对于调用file_get_contents() ),并将一个文件附加到名为Array.dat的电子邮件中,而不是所选文件。 我究竟做错了什么?

Warning: file_get_contents() expects parameter 1 to be a valid path, array given in C:\wamp\www\myapp\submit.php on line 188

HTML:

<input id="file" name="file[]" type="file" multiple="true">

PHP:

$fullmessage = "This is a multi-part fullname in MIME format.

--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"

--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: quoted-printable

$msg_quoted

--_2_$boundary--\r\n";

$msg_b64 = base64_encode($msg);

$fullmessage .= "--_1_$boundary
Content-Type: application/octet-stream; name=\"".$date->format('U')."-".$company."-".$custname."-".$email.".txt\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

$msg_b64\r\n";

foreach($_FILES as $f){
  if($f['size'] > 0){
  $attachment = chunk_split(base64_encode(file_get_contents($f['tmp_name'])));
   $name = $f['name'];

   $fullmessage .= "--_1_$boundary
Content-Type: application/octet-stream; name=\"$name\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

$attachment\r\n";
  }
}

$fullmessage .= "--_1_$boundary--";
$mail_options = '';
$mail_options .= 'O DeliveryMode=b'; //tells sendmail to run asynchronously
mail(EMAIL_RECIPIENTS, $subject, $fullmessage, $headers, $mail_options);

更新:由于@ I'L'I,此问题已解决:

// Process the uploaded files.
$num_files = count($_FILES['file']['tmp_name']);

for($i=0; $i < $num_files; $i++){   
    if($_FILES['file']['size'][$i] > 0){
        $attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'][$i])));
        $name = $_FILES['file']['name'][$i];

        $fullmessage .= "--_1_$boundary
Content-Type: application/octet-stream; name=\"$name\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

$attachment\r\n";
  }  
}

通常,仅使用一个文件输入元素就不能上传多个文件。 我遇到的唯一支持它的浏览器是Opera,他们删除了该功能,可能是由于缺乏服务器端支持。

这就是您要经历的:如果将表单字段的名称从单个名称更改为指向数组,则必须在PHP端更改对文件数据的访问。 如果您说您不能使用一个像样的库进行邮件发送,那么我认为您不能更改接收文件的PHP代码。 这样就无法将单文件上传更改为多文件上传。

并且请考虑不要尝试在HTML端创建这样的多文件输入字段,因为没有用户知道他可能能够发送多个文件-即使您告诉他们可以,他们也不知道如何发送。

我认为这个问题更多是由错误指示引起的:

警告:file_get_contents()期望参数1为有效路径,第188行的C:\\ wamp \\ www \\ myapp \\ submit.php中给出的数组。

file_get_contents需要一个string而不是一个array

因此,您可以采取以下措施来解决此问题:

请使用正确的字符串:

  $attachment = chunk_split(base64_encode(file_get_contents($f)));

或使用$_FILES数组的key

for ($x=0; $x<sizeof($_FILES); $x++) {
    $attachment = chunk_split(base64_encode(file_get_contents($_FILES[$x])));
} 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM