Emailing File Attachments

This is a way to accept multiple file uploads from a file input on a form. You can make an array of acceptable file types to attach and it will compare the input file extension against them.

                                if(isset($_FILES['fileInputName']['name']) 
	&& (bool) $_FILES['fileInputName']['name']){
	foreach($_FILES as $name=>$file){
		$file_name = $_FILES['fileInputName']['name'];
		$temp_name = $_FILES['fileInputName']['tmp_name'];
		$file_type = $_FILES['fileInputName']['type'];
		
		//get extension of file
		$base = basename($file_name);
		$allowedTypes = array('pdf');
		$files = array();
		
		//check validity of file
		$path_parts = pathinfo($file_name);
		$ext = $path_parts['extension'];
		
		if(!in_array($ext, $allowedTypes)){
			$resError = '* Invalid File Type';
			echo '<span class="required">* Application Not Submitted</span>';
		}else{
			//move to server
			$server_file = "/home/yoursite/attachments/{$path_parts['basename']}";
			move_uploaded_file($temp_name, $server_file);
			
			//add to file array
			array_push($files, $server_file);
		}
	}
}
                            

Now we need to define the headers and boundary for the message.

                                $msg = "Your message with input info";
$headers = "From: {$from}";
                    
//define boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";

//tell header about boundary
$headers .= "\\nMIME-Version: 1.0\\n";
$headers .= "Content-Type: multipart/mixed;\\n";
$headers .=" boundary=\\"{$mime_boundary}\\"";

//define plain text email
$message = "\\n\\n--{$mime_boundary}\\n";
$message .= "Content-Type: text/plain; charset=\\"iso-8859-1\\"\\n";
$message .= "Content-Transfer-Encoding: 7bit\\n\\n" . $msg . "\\n\\n";
$message .= "--{$mime_boundary}\\n";
                            

Now we can loop through each file in the array and define attachments.

                                foreach($files as $file){
    $aFile = fopen($file, "rb");
    $data = fread($aFile, filesize($file));
    fclose($aFile);
    $data = chunk_split(base64_encode($data));
    $file = $path_parts['basename'];
    $message .= "Content-Type: {\\"application/octet-stream\\"};\\n";
    $message .= " name=\\"{$file}\\"\\n";
    $message .= "Content-Disposition: attachment;\\n";
    $message .= " filename=\\"{$file}\\"\\n";
    $message .= "Content-Transfer-Encoding: base64\\n\\n" . $data . "\\n\\n";
    $message .= "--{$mime_boundary}\\n";
}
mail($to, $subject, $message, $headers);