[英]How to send an Encrypted Zip Archive as Mail Attachment in PHP?
我找到了有關加密 zip 文件以及如何在郵件附件中發送文件的答案。 兩者都在單獨的問題中。 所以我把兩者結合起來,讓別人更容易。 這是一個自我回答的問題。
您將能夠為每個接收者生成一個隨機的唯一密碼,並將密碼與郵件中的附件一起發送。
注意:大多數服務器會將附件標記為不安全,因為它們無法掃描 zip 存檔中的惡意文件。
以下是在 PHP 中將加密的 Zip 存檔作為郵件附件發送的代碼。
<?php
$file_key="password"; //Password for the Zip Archive
$receiver_name = "Receiver Name";
$receiver_email = "Receiver Email";
$sender_name = "Sender Name";
$sender_mail = "Sender Mail";
//Main Content
$main_subject = "Mail Subject";
$main_body = "Mail Body";
echo "Creating Zip Archive <br>";
$zip = new ZipArchive();
$filename = "final-level.zip"; //Zip File Name
if ($zip->open($filename, ZipArchive::CREATE)===TRUE) {
$zip->setPassword($file_key);
$zip->addFile(
"./dir/test.txt", //File Directory
"test.txt" //New File Name inside Zip Archive
);
$zip->setEncryptionName('text.txt', //New File Name
ZipArchive::EM_AES_256); //Encryption
$zip->close();
}else{
echo "Cannot open Zip file <br>";
exit("cannot open <$filename>\n");
}
echo "Created Zip File <br>";
//#############################DO NOT CHANGE ANYTHING BELOW THIS LINE#############################
$file = chunk_split(base64_encode(file_get_contents($filename)));
$uid = md5(uniqid(time()));
//Sending mail to Server
$retval = mail($receiver_email, $main_subject, "--$uid\r\nContent-type:text/html; charset=iso-8859-1\r\nContent-Transfer-Encoding: 7bit\r\n\r\n$main_body \r\n\r\n--$uid\r\nContent-Type: application/octet-stream; name=\"$filename\"\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"$filename\"\r\n\r\n$file\r\n\r\n--$uid--", "From: $sender_name <$sender_mail>\r\nReply-To: $sender_mail\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$uid\"\r\n\r\n");
//#############################DO NOT CHANGE ANYTHING ABOVE THIS LINE#############################
//Output
if ($retval == true) {
echo "Message sent successfully...";
} else {
echo "Error<br>";
echo "Message could not be sent...Try again later";
}
//Delete File from Server
if (file_exists($filename)) {
unlink($filename);
}
echo "Unlinked File from Server <br>";
echo "Done <br>";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.