上传多个文件并进行处理

时间:2014-07-21 08:29:32

标签: php mysql file-upload

我只想从this question关注多个邮件附件。

我在stackoverflow上查看过各种网站,包括verens.comHTML 5 multi file upload with PHP,我遇到了一些问题。

我正在尝试将文件移动到文件夹,将内容添加到数据库并将其作为电子邮件发送。这就是我变得不稳定的地方。它正在处理lest文件,但不是其他任何文件。

这就是我对代码的要求(来自verens.com)

$files = array();
$fdata = $_FILES['attachment'];

if(is_array($fdata['name']))
{
    for($i = 0; $i < count($fdata['name']); ++$i)
    {
        $files[] = array(
            $name_of_file = $_FILES['attachment']['name'][$i], //[$count];
            $file_name = $guid."-".$name_of_file,
            $temp_name = $_FILES['attachment']['tmp_name'][$i], //[$count];
            $file_type = $_FILES['attachment']['type'][$i], //[$count];
            $file_size = $_FILES['attachment']['size'][$i], //[$count];
        );

    }
}
else $files[] = $fdata;

foreach ($files as $file)
{
    (another snippet in the question)
}

当我打印出阵列时,这就是我所拥有的:

Array ( 
    [attachment] => Array ( 
        [name] => Array ( 
            [0] => 96681331.jpg 
            [1] => 96681332.jpg 
            [2] => 96681333.jpg 
            [3] => 96689957.jpg 
          ) 
        [type] => Array ( 
            [0] => image/jpeg 
            [1] => image/jpeg 
            [2] => image/jpeg 
            [3] => image/jpeg 
        ) 
    [tmp_name] => Array ( 
        [0] => C:\xampp\tmp\phpFD95.tmp 
        [1] => C:\xampp\tmp\phpFD96.tmp 
        [2] => C:\xampp\tmp\phpFD97.tmp 
        [3] => C:\xampp\tmp\phpFDA8.tmp 
    ) 
    [error] => Array ( 
        [0] => 0 
        [1] => 0 
        [2] => 0 
        [3] => 0 
    ) 
    [size] => Array ( 
        [0] => 15256 
        [1] => 13672 
        [2] => 10451 
        [3] => 14356 
    )
  ) 
) 

正如你所看到的,它正在拾取数组中的所有文件,它只是处理最后一个文件。

以下是满足那些无益评论的相关代码!试图让问题易于理解,你没有任何荣誉!

if ($file_size > 2048000)
{
    header ("refresh: 5; url=attach.php");
    include ("header.php");
    echo "File size is to big. Size must be no bigger than 2Mb. Please go <a href='attach.php'>back</a>";
    include ("footer.php");
    exit;
}
else
{
    $pics = array(".bmp", ".gif", ".jpg", "jpeg", ".png"); //5
    $docs = array(".doc", "docx", ".odt", ".pdf", ".ppt", "pptx", ".rtf", ".txt", ".xls", "xlsx"); //10
    $misc = array(".csv", ".htm", "html", ".php", ".pkt", ".rar", ".sql", ".xpi", ".zip"); //9

    $base = basename($file_name);
$extension = substr($base, strlen($base)-4, strlen($base));
$extension = strtolower($extension);

if (in_array($extension,$pics))
{
    $target = "".FILES."/".FUP_PICS."/";
}

if (in_array($extension,$docs))
{
    $target = "".FILES."/".FUP_DOCS."/";
}

if (in_array($extension,$misc))
{
    $target = "".FILES."/".FUP_MISC."/";
}

$target = $target.$base;

$allowed_extensions = array(".bmp", ".csv", ".doc", "docx", ".gif", ".htm", "html",
            ".jpg", ".JPG", "jpeg", "JPEG", ".odt", ".pdf", ".php", ".pkt", ".png", ".ppt", "pptx",
            ".rtf", ".sql", ".txt", ".xls", "xlsx", ".zip"
            );

if(in_array($extension,$allowed_extensions)) 
{
    $from = ($_POST['from']);
    $emailfrom = "bad-mailbox@chriswilcox.me.uk";
    $emailto = "bad-mailbox@chriswilcox.me.uk";
    $bcc = ($_POST['bcc']);
    $subject = htmlspecialchars($_POST['subject']);
    $sig = ($_POST['sig']);
    $message = htmlspecialchars($_POST['message'], ENT_NOQUOTES);
    $message1 = htmlspecialchars_decode($_POST['message'], ENT_QUOTES);
    if ($sendhash == 'Y')
    {
        $message1 .= "\n\nThe following is your unique message ID: ";
        $message1 .= $guid;
        $message1 .= "\n\nAttachment has been scanned for viruses and is virus free.";
        $message1 .= "\n\nPlease make sure the first part of the file name matches the unique message ID. If it does not, please DO NOT open the file";
        $message1 .= "\n\nTo verify the validity of the message, click the link below or copy and paste it into your browser:";
        $message1 .= "\n\n ";
        $message1 .= HTTP_PATH;
        $message1 .= "verify.php?uid=";
        $message1 .= urlencode($guid);
        $message1 .= "\n\nPlease note, verification link expires on ";
        $message1 .= $expirydate;
    }
    else
    {
    }
    if ($signature == 'Y')
    {
        if ($sig == "")
        {
            $message1.= "\n\n--\n Sent from Chris' Address Book";
        }
        else
        {
            $message1 .= "\n\n--\n".$sig;
        }
    }
    else
    {
    }

    $file = $temp_name;
    $content = chunk_split(base64_encode(file_get_contents($file)));
    $uid = md5(uniqid(time()));

    if ($from == 'other')
    {
        $header = "From: ".$emailfrom."\r\n";
        $header .= "Reply-To: ".$emailfrom."\r\n";
        $from = $emailfrom;
    }
    else
    {
        $header = "From: ".$from."\r\n";
        $header .= "Reply-To: ".$from."\r\n";                               
    }
    $header .= "Bcc: ".$bcc."\r\n";
    $header .= "MIME-Version: 1.0\r\n";

    $header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
    $header .= "This is a multi-part message in MIME format. \r\n";

    $header .= "--".$uid."\r\n";
    $header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
    $header .= $message1."\r\n";

    $header .= "--".$uid."\r\n";
    $header .= "Content-Type: ".$file_type."; name=\"".$file_name."\"\r\n";
    $header .= "Content-Transfer-Encoding: base64\r\n";
    $header .= "Content-Disposition: attachment; filename=\"".$file_name."\"\r\n\r\n";
    $header .= $content."\r\n";

    if ($_POST['emailto'] == '')
    {
        try 
        {
            $esql = $conn->prepare("SELECT * FROM ".PERSON." JOIN contact ON contact.personID = person.adbkid WHERE email1 = '$bcc' OR email2 = '$bcc'");
            $esql->execute();

            $esql->bindColumn('adbkid', $aid);
            $esql->bindColumn('pid', $pid);

            $esqlc = $conn->prepare("SELECT COUNT(*) FROM ".PERSON." JOIN contact ON contact.personID = person.adbkid WHERE email1 = '$bcc' OR email2 = '$bcc'");
            $esqlc->execute();

            $num = $esqlc->fetchColumn();
        }
        catch (PDOException $e)
        {
            print '<div class="sqlerror">'.$e->getMessage().'</div>';
        }
    }
    else
    {
        try
        {
            $esql = $conn->prepare("SELECT * FROM ".PERSON." JOIN contact ON contact.personID = person.adbkid WHERE email1 = '$emailto' OR email2 = '$emailto'");
            $esql->execute();

            $esql->bindColumn('adbkid', $aid);
            $esql->bindColumn('pid', $pid);

            $esqlc = $conn->prepare("SELECT COUNT(*) FROM ".PERSON." JOIN contact ON contact.personID = person.adbkid WHERE email1 = '$emailto' OR email2 = '$emailto'");
            $esqlc->execute();

            $num = $esqlc->fetchColumn();
        }
        catch (PDOException $e)
        {
            print '<div class="sqlerror">'.$e->getMessage().'</div>';
        }
    }

    while ($esql->fetch(PDO::FETCH_BOUND))
    {                           
        if ($num == 0)
        {
            $selfid = "EMAILSA";
        }
        else
        {
            $selfid = $aid;
        }
    }

    if (mail($emailto, $subject, "", $header)) 
    {
        if ($sendhash == 'Y')
        {
            try
            {
                // $sql=mysql_query("INSERT INTO ".EMAILS." (emailfrom, emailto, bcc, subject, message, getthedate, gettime, randhash, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID) VALUES ('$from', '$emailto', '$bcc', '$subject', '$message', '$getthedate', '$gettime', '$guid', '$file_name', '$extension', '$showinsearch', '$expireit', '$siv', '$wv', '$selfid')"); 
                $hsql = $conn->prepare("INSERT INTO ".EMAILS." 
                (emailfrom, emailto, bcc, subject, message, getthedate, gettime, randhash, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID)
                VALUES
                (:from, :et, :bcc, :sub, :msg, :gd, :gt, :guid, :fn, :fe, :sis, :ex, :siv, :wv, :aid)");

                $hsql->bindValue(':from', $from);
                $hsql->bindValue(':et', $emailto);
                $hsql->bindValue(':bcc', $bcc);
                $hsql->bindValue(':sub', $subject);
                $hsql->bindValue(':msg', $message);
                $hsql->bindValue(':gd', $getthedate);
                $hsql->bindValue(':gt', $gettime);
                $hsql->bindValue(':guid', $guid);
                $hsql->bindValue(':fn', $file_name);
                $hsql->bindValue(':fe', $extension);
                $hsql->bindValue(':sis', $showinsearch);
                $hsql->bindValue(':ex', $expireit);
                $hsql->bindValue(':siv', $siv);
                $hsql->bindValue(':wv', $wv);
                $hsql->bindValue(':aid', $selfid);

                $hsql->execute();

                $lastid = $conn->lastInsertId();

                $sqlrh = $conn->prepare("INSERT INTO ".HASH." (randhash) VALUES (:guid)");

                $sqlrh->bindValue(':guid', $guid);

                $sqlrh->execute();
            }
            catch (PDOException $e)
            {
                print '<div class="sqlerror">'.$e->getMessage().'</div>';
            }
        }
        else
        {
            $hsql = $conn->prepare("INSERT INTO ".EMAILS." 
            (emailfrom, emailto, bcc, subject, message, getthedate, gettime, fileatt, fileext, showinsearch, expireit, showinverify, wasviewed, personID)
            VALUES
            (:from, :et, :bcc, :sub, :msg, :gd, :gt, :fn, :fe, :sis, :ex, :siv, :wv, :aid)");

            $hsql->bindValue(':from', $from);
            $hsql->bindValue(':et', $emailto);
            $hsql->bindValue(':bcc', $bcc);
            $hsql->bindValue(':sub', $subject);
            $hsql->bindValue(':msg', $message);
            $hsql->bindValue(':gd', $getthedate);
            $hsql->bindValue(':gt', $gettime);
            $hsql->bindValue(':fn', $file_name);
            $hsql->bindValue(':fe', $extension);
            $hsql->bindValue(':sis', $showinsearch);
            $hsql->bindValue(':ex', $expireit);
            $hsql->bindValue(':siv', $siv);
            $hsql->bindValue(':wv', $wv);
            $hsql->bindValue(':aid', $selfid);

            $hsql->execute();

            $lastid = $conn->lastInsertId();                            
        }
        try
        {
            $fsql = $conn->prepare("INSERT INTO ".SENTFILES." 
            (filename, filetype, fileext, filesize, filetempname, dateadded, timeadded, fileguid, sentmailid) 
            VALUES 
            (:fn, :ft, :fe, :fs, :tn, :gd, :gt, :guid, :li)");

            $fsql->bindValue(':fn', $file_name);
            $fsql->bindValue(':ft', $file_type);
            $fsql->bindValue(':fe', $extension);
            $fsql->bindValue(':fs', $file_size);
            $fsql->bindValue(':tn', $temp_name);
            $fsql->bindValue(':gd', $getthedate);
            $fsql->bindValue(':gt', $gettime);
            $fsql->bindValue(':guid', $guid);
            $fsql->bindValue(':li', $lastid);

            $fsql->execute();                               

            $expire = $conn->prepare("UPDATE ".EMAILS." SET showinverify = 0 WHERE expireit < CURDATE()");
            $expire->execute();
        }
        catch (PDOException $e)
        {
            print '<div class="sqlerror">'.$e->getMessage().'</div>';
        }
        //header ("refresh: 5; url=$url");
        include ("header.php");
        $ful = (move_uploaded_file($temp_name, $target)) ? "".$file_name." was uploaded to ".$target."" : "".$file_name.", was not uploaded. Please try a manual upload.";
        echo "<title>Success sending email</title>";
        echo "Your message has been successfully sent.<br/><br/>Message details have been added to the database.<br/><br/>$ful";
        echo "<br/><br/>";
        print_r($_FILES);
        include ("footer.php");
    }
    else
    {
        //header ("refresh: 5; url=$url");
        include ("header.php");
        echo "<title>Error sending email</title>";
        echo "There seems to be an error sending your email.";
        include ("footer.php");
    }
    exit;
}
else
{
    //header ("refresh: 5; url=attach.php");
    include ("header.php");
    echo "File type is not allowed. Please go <a href='attach.php'>back</a>";
    echo"<br/><br/>";
    print_r($_FILES);
    include ("footer.php");
    exit;
}

}

我也尝试过以下代码无效:

foreach ($_FILES['attachment']['tmp_name'] as $key => $tmp_name) 
{
    $name_of_file = $_FILES['attachment']['name'][$key];
    $file_name = $guid."-".$name_of_file;
    $temp_name = $_FILES['attachment']['tmp_name'][$key];
    $file_type = $_FILES['attachment']['type'][$key];
    $file_size = $_FILES['attachment']['size'][$key];
}

就像我说的那样,它只是获取数组中的最后一个值而且我不确定我哪里出错了。

我在文件数组周围尝试了foreach,然后在pastebin中的整个代码周围尝试了它,它导致了相同的结果。令人困惑的是文件在数组中。

我是否有任何明显的缺失,指针最有帮助。

提前致谢。

1 个答案:

答案 0 :(得分:1)

这套代码对我来说很好。

    $files = array();
    $fdata = $_FILES['attachment'];
    if(is_array($fdata['name']))
    {
        for($i = 0; $i < count($fdata['name']); ++$i)
        {
            $name_of_file = $_FILES['attachment']['name'][$i];
            $temp_name = $_FILES['attachment']['tmp_name'][$i];
            move_uploaded_file($temp_name, "./$name_of_file");
        }
    }
    //echo "<pre>";print_r($files);

所有文件都上传到同一个文件夹中。希望这会对你有所帮助。