我尝试使用此代码使用PHP 5.5上传多个文件并附加到电子邮件中。如果我在file[]
字段的file
属性上使用name
括号(所以它为input
),我就能成功上传一个档案;如果我重新打开括号,页面会发出此警告(对于调用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&#39; L&#39;我:
// 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";
}
}
答案 0 :(得分:1)
通常只能使用一个文件输入元素上传多个文件。我遇到的唯一支持它的浏览器是Opera,他们删除了该功能,可能是因为缺乏服务器端支持。
这正是您遇到的问题:如果您将表单字段的名称从单个名称更改为指向数组,则必须更改对PHP端文件数据的访问权限。如果你说你不能使用一个像样的邮件库,我假设你不能改变接收文件的PHP代码。然后,您无法将单文件上载更改为多文件上载。
请考虑不要在HTML端创建这样的多文件输入字段,因为没有用户知道他可能能够发送多个文件 - 即使你告诉他们他们可以,他们也不会我知道怎么做。
答案 1 :(得分:1)
我认为这个问题更多的是错误表明的问题:
警告: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)));
或使用key
数组的$_FILES
for ($x=0; $x<sizeof($_FILES); $x++) {
$attachment = chunk_split(base64_encode(file_get_contents($_FILES[$x])));
}