PHPMailer文件上传是否正确

PHPMailer file upload is this correct

您好,我一直在努力寻找构建文件上传的正确方法。在很多帮助下,我设法让它工作,但我想确保我想出的是正确和安全的。这是完整的代码。我想到的一件事是,如果我将文件移动到临时目录,然后将它们压缩到所需的目录,文件是否仍然存在于临时目录中?我需要删除那些吗?

完整代码如下:

// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'autoloader.php';

$mail = new PHPMailer(true);



$clean_email = filter_var($_POST['appEmail'],FILTER_SANITIZE_EMAIL);


$files = "";
$target_dir = $_SERVER['DOCUMENT_ROOT'] . "/XXXXXXX/uploads/";

$dateKey = date( 'd-m-Y--H-i-s' );

function clean($string) {
    $string = str_replace(' ', '-', $string); // Replaces all spaces with hyphens.

    return preg_replace('/[^A-Za-z0-9\-]/', '', $string); // Removes special chars.
}

function compressImage($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
    } elseif ($info['mime'] == 'image/gif') {
        $image = imagecreatefromgif($source);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
    }

    imagejpeg($image, $destination, $quality);

}

if(isset($_FILES)) {



    $uploadOk = 1;
    $fileString = '';

    $fileMessage = 'FILEERROR(';

    $files = $_FILES;


    foreach ( $files as $key => $file ) {

        $uploadfile = tempnam(sys_get_temp_dir(), hash('sha256', $file['name']));

        if (move_uploaded_file($file['tmp_name'], $uploadfile)) {



//get the file extension
        $imageFileExt = strtolower( pathinfo( $file["name"], PATHINFO_EXTENSION ) );


// get the file type
        $target_file = $target_dir . basename($file["name"]);

        $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));


// get file size
        $check = getimagesize($uploadfile);
        if($check === false) {
            $fileMessage .=  $key."=noimage,";
            $uploadOk = 0;
            $msg.="noimage";
        }

// Allow certain file formats

        else if($imageFileType !== "jpg" && $imageFileType !== "png" && $imageFileType !== "jpeg"
                && $imageFileType !== "gif" ) {
            $fileMessage .=  $key."=wrongfile,";
            $uploadOk = 0;
            $msg.="wrongeimage";
        }

// Check if file already exists
        else if (file_exists($target_file)) {
            $fileMessage .=  $key."=fileexists,";
            $uploadOk = 0;
            $msg.="fileexists";
        }


// Check file size
        else if ($file["size"] > 20000000) { //20mb
            $fileMessage .=  $key."=toobig,";
            $uploadOk = 0;

            $msg.="toobig";

        } else {

            //create a new name for the file
//the persons name plus file field plus date plus time plus file extension
//such as :joe_bloggs_bank_statement_1_9_10_21_10_55.jpg
//and joe_bloggs_pay_slip_1_9_10_21_10_55.jpg


            $fileName = clean($_POST['appName']). "_" . $key . "_" . $dateKey . "." . $imageFileType;
            compressImage($uploadfile, $target_dir . basename( $fileName ), 60);



            $msg .= "comp";
        }



// creates a set of links to the uploaded files on the server
        // to be placed in the body of the email (the files themselves do not get attached in the email
        $fileString .= strtoupper($key).": <a href='XXXXXXXX/uploads/".$file['name']."'>".$file['name']."</a><br>";

        $msg.="upload success";

    } else{
            $msg.="cant upload files";
        }
    }
    $fileMessage .= ')';


}






try {
    //Server settings
    //$mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'mail.XXXXXXXXX.com';                    // Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'XXX@XXXXXXX.com';                     // SMTP username
    $mail->Password   = 'XXXXXXXXXX';                               // SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
    $mail->Port       = 587;                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

    //Recipients
    $mail->setFrom( 'XXX@XXXXXXXXX.com', 'Mailer' );
    $mail->addAddress( 'XXXXX@XXXXXXXXX.com', 'Recipient' );     // Add a recipient

    $mail->addReplyTo( $_POST['appEmail'], 'Information' );


    // Content
    $mail->isHTML( true );                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();


    echo 'Message sent successfully'.$msg;
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

move_uploaded_file() 做它所说的:它 移动 文件,因此它不再在原始临时目录中,而是在您将其移动到的任何位置。

您的一系列 if/elseif 检查只会匹配一个问题 – 如果您一次检测到所有问题而不是一次只检测一个问题,对您的用户来说会更好,所以大多数 elseifs 应该只是 ifs.

这看起来不对:

if (file_exists($target_file)) {

$target_file 包含原始 user-supplied 文件名,而不是移动后的文件名 ($uploadfile),因此我不希望存在具有该名称的文件。

这看起来像是打字错误:$msg.="wrongeimage";