将$ _FILES [' name']作为列表发送电子邮件

时间:2014-11-04 20:51:42

标签: php arrays foreach each

用户完成上传多个文件后,我会显示屏幕上传的文件。我也试图将相同的列表包含在电子邮件正文中。绝对一切都有效,包括在屏幕上显示每个文件,除了$ message_body只列出数组中的最后一个文件名。任何想法??

<!DOCTYPE html>
<html>
<head>
<title>upload</title>
</head>
<body>
<?php

if(isset($_POST['ship-it']) AND $_POST['ship-it'] === "yes") {
    $yesupload = $_POST['ship-it'];
    preg_match("/yes/", "".$yesupload."");

    for($i=0; $i<count($_FILES['tray']['name']); $i++) {
         $filename = $_FILES['tray']['name'][$i];
         $s_name = $_FILES['tray']['tmp_name'][$i];
         move_uploaded_file($s_name, 'https://example.com/inbox/'.$filename.'');
    }
    $info = $_SERVER['HTTP_USER_AGENT'];
    $message_body = "".$_POST["email"]." uploaded the file: ".$_FILES['tray']['name']."
    https://example.com/inbox/".rawurlencode($filename)."

    User Agent: ".$_POST["id"]." ".$info."";

    $mail_options = [
        'sender' => 'sender@gmail.com',
        'to' => 'receiver@gmail.com',
        'subject' => 'new file sent',
        'textBody' => $message_body
    ];

    try {
        $message = new Message($mail_options);
        $message->send();
    } catch (InvalidArgumentException $e) {
        echo 'error: ';
    }
    echo "<p>All done. Here's what you sent:</p>";
    for($i = 0; $i < count($_FILES['tray']['name']); $i++)
    {
        echo "<ul style='list-style-type:square'>
            <li>{$_FILES['tray']['name'][$i]}</li>
            </ul>";
    }
}
?>
<form action="<?php echo $upload_url?>" method="post" enctype="multipart/form-data">
   <p>Files to upload: </p> <br>
   <input type="hidden" name="ship-it" value="yes">
   <input type="hidden" name="id" value="<?php echo $_SERVER['REMOTE_ADDR']?>">   
   <input type="email" name="email" required="" autofocus placeholder="Your email address"><br><br>
   <input type="file" multiple name="tray[]"  required="">
   <input  type="submit" value="Upload"><br><br>
</form>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

您已经有一个循环,在网页上显示文件名。您需要一个类似的循环来存储$message_body中的文件名。您可以将其合并到已有的用于移动上载文件的循环中。也许是这样的:

$message_body = "".$_POST["email"]." uploaded these files:\n";

for($i=0; $i<count($_FILES['tray']['name']); $i++) {

  $filename = $_FILES['tray']['name'][$i];
  $s_name = $_FILES['tray']['tmp_name'][$i];
  move_uploaded_file($s_name, 'https://example.com/inbox/'.$filename.'');

  $message_body .= "* " . $_FILES['tray']['name'][$i]
                .  "-> https://example.com/inbox/" . rawurlencode($filename)
                .  "\n";
}

答案 1 :(得分:0)

您之前的代码似乎将$_FILES['tray']['name']视为数组。您是否尝试使用逗号将其从数组转换为字符串:

 $message_body = "".$_POST["email"]." uploaded the file: ".implode(", ",$_FILES['tray']['name'])."https://example.com/inbox/".rawurlencode($filename)."