PHPMailer attachment type and size limit

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-20 05:35:06

问题


i have one form and i am using PHPMailer to send data from that form to my email. Users can send attachments as well, but i have one rpoblem: how to make PHPMailer to deny attachments larger than 2Mb and to allow only iamge attachments (no other types of documents)?

This is code i using for multiply email attachments with PHPMailer:

foreach(array_keys($_FILES['fileAttach']['name']) as $key) {

   $source = $_FILES['fileAttach']['tmp_name'][$key]; 
   $filename = $_FILES['fileAttach']['name'][$key]; 

   $mail->AddAttachment($source, $filename);

}

回答1:


you can check the filesize using filesize() and the type using mime_content_type().

the resulting code could look like:

$maxsize = 2 * 1024 * 1024; // 2 MB
$types = array('image/png', 'image/jpeg', 'image/gif'); // allowed mime-types

if(filesize($filename) < $maxsize && in_array(mime_content_type($filename),$types)){
  $mail->AddAttachment($source, $filename);
}

EDIT: PHPMailer doesn't have a built-in possibility for those chacks - as you can see from the source, it only checks if the file exists when adding an attachment:

if ( !@is_file($path) ) {
  throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
}



回答2:


Use filesize() for checking the file size. For checking if the file is a image use getimagesize() which returns false if it's not an image, else it will return an array of info including mimetype (if you wan't to check for specific image types).



来源:https://stackoverflow.com/questions/10947228/phpmailer-attachment-type-and-size-limit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!