PHP problem with for each $_FILES

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

PHP problem with for each $_FILES

Post by cjkeane »

Hi Everyone,
I'm having an issue with my coding and I'm not sure where the issue is. I'm using phpmailer to handle sending an email with attachments which functions correctly. The issue I'm having is in the coding to get the filenames and extensions from $_FILES where the code starts from foreach($_FILES as $userfile) and ends just before if(!$mail->Send()). If I exclude that entire section, then I receive emails with attachments and text in the body of the message. If I include that code, but type content in the body of the message only, then I receive the email successfully. If I send the message with an attachment, then the email arrives with no message in the body and no attachments. I'm stumped. Any help would be appreciated.

Code: Select all

       if(isset($_POST['Send'])) {
              $allowtypes=array("zip", "rar", "doc", "pdf", "jpg", "gif", "jpeg", "odt", "ott", "sxw", "ods", "wpd", "xml", "htm", "rtf", "xls", "bmp", "tif", "tiff", "png", "txt");
              $requirefile="true";
              $max_file_size="20480";	
              $errors = array(); 
              if (empty($_POST['emailTo']) ) {$errors[]='One or more email addresses are required on the Send To line.';	} 
              if (empty($_POST['emailSubject']) ) {$errors[]='An email Subject is required'; }
              if (empty($_POST['ActionTextField']) ) {$errors[]='A message is required.';	}		
              if((!empty($_FILES["attachment1"])) && ($_FILES['attachment1']['error'] == 0)) {
              $filename1 = basename($_FILES['attachment1']['name']);
                     $ext1 = substr($filename1, strrpos($filename1, '.') + 1);
                     $filesize1=$_FILES['attachment1']['size'];
                                $max_bytes1=$max_file_size*1024;
                                if (!in_array($ext1, $allowtypes)) {
                                    $errors[]="Invalid extension for your file: <strong>".$filename1."</strong> (Please View Important Notes for permitted attachment types.)";
                                } elseif($filesize1 > $max_bytes1) {
                                    $errors[]= "Your file: <strong>".$filename1."</strong> is to big. Max file size is ".$max_file_size."kb.";
                                }
                            } 				
                            if((!empty($_FILES["attachment2"])) && ($_FILES['attachment2']['error'] == 0)) {
                                $filename2 = basename($_FILES['attachment2']['name']);
                                $ext2 = substr($filename2, strrpos($filename2, '.') + 1);
                                $filesize2=$_FILES['attachment2']['size'];
                                $max_bytes2=$max_file_size*1024;
                                if (!in_array($ext2, $allowtypes)) {
                                    $errors[]="Invalid extension for your file: <strong>".$filename2."</strong> (Please View Important Notes for permitted attachment types.)";
                                } elseif($filesize2 > $max_bytes2) {
                                    $errors[]= "Your file: <strong>".$filename2."</strong> is to big. Max file size is ".$max_file_size."kb.";
                                }
                            } 
                            if((!empty($_FILES["attachment3"])) && ($_FILES['attachment3']['error'] == 0)) {
                                $filename3 = basename($_FILES['attachment3']['name']);
                                $ext3 = substr($filename3, strrpos($filename3, '.') + 1);
                                $filesize3=$_FILES['attachment3']['size'];
                                $max_bytes3=$max_file_size*1024;
                                if (!in_array($ext3, $allowtypes)) {
                                    $errors[]="Invalid extension for your file: <strong>".$filename3."</strong> (Please View Important Notes for permitted attachment types.)";
                                } elseif($filesize3 > $max_bytes3) {
                                    $errors[]= "Your file: <strong>".$filename3."</strong> is to big. Max file size is ".$max_file_size."kb.";
                                }
                            } 
                            if((!empty($_FILES["attachment4"])) && ($_FILES['attachment4']['error'] == 0)) {
                                $filename4 = basename($_FILES['attachment4']['name']);
                                $ext4 = substr($filename4, strrpos($filename4, '.') + 1);
                                $filesize4=$_FILES['attachment4']['size'];
                                $max_bytes4=$max_file_size*1024;
                                if (!in_array($ext4, $allowtypes)) {
                                    $errors[]="Invalid extension for your file: <strong>".$filename4."</strong> (Please View Important Notes for permitted attachment types.)";
                                } elseif($filesize4 > $max_bytes4) {
                                    $errors[]= "Your file: <strong>".$filename4."</strong> is to big. Max file size is ".$max_file_size."kb.";
                                }
                            } 
                            if((!empty($_FILES["attachment5"])) && ($_FILES['attachment5']['error'] == 0)) {
                                $filename5 = basename($_FILES['attachment5']['name']);
                                $ext5 = substr($filename5, strrpos($filename5, '.') + 1);
                                $filesize5=$_FILES['attachment5']['size'];
                                $max_bytes5=$max_file_size*1024;
                                if (!in_array($ext5, $allowtypes)) {
                                    $errors[]="Invalid extension for your file: <strong>".$filename5."</strong> (Please View Important Notes for permitted attachment types.)";
                                } elseif($filesize5 > $max_bytes5) {
                                    $errors[]= "Your file: <strong>".$filename5."</strong> is to big. Max file size is ".$max_file_size."kb.";
                                }
                            } 
                            if (empty($errors)) { 
				$to = $_POST['emailTo'];
                                $from = $_POST['emailFrom'];
                                $emailfromname = $_POST['emailFromName'];
                                $emailcc = $_POST['emailcc'];	
                                $emailbcc = $_POST['emailbcc'];	
                                $subject = $_POST['emailSubject'];
                                require_once 'class.phpmailer.php';
                                $mail = new PHPMailer();
                                $mail->CharSet = 'UTF-8';
                                $mail->IsHTML(true);
                                $mail->From = $from;
                                $mail->FromName = $emailfromname;
                                $mail->AddAddress($to);
                                if(!empty($emailcc)){ $mail->AddCC(trim($emailcc)); } 
                                if(!empty($emailbcc)){ $mail->AddBCC(trim($emailbcc)); } 
                                $mail->Subject = "RE: " . ($subject);
                                $mail->Body =  $_POST['ActionTextField']; 
                                $mail->AltBody  =  rip_tags($_POST['ActionTextField']); 
                                if (isset($_FILES['attachment1']) && $_FILES['attachment1']['error'] == UPLOAD_ERR_OK) {
                                    $mail->AddAttachment($_FILES['attachment1']['tmp_name'], $_FILES['attachment1']['name']);
                                }
                                if (isset($_FILES['attachment2']) && $_FILES['attachment2']['error'] == UPLOAD_ERR_OK) {
                                    $mail->AddAttachment($_FILES['attachment2']['tmp_name'], $_FILES['attachment2']['name']);
                                }
                                if (isset($_FILES['attachment3']) && $_FILES['attachment3']['error'] == UPLOAD_ERR_OK) {
                                    $mail->AddAttachment($_FILES['attachment3']['tmp_name'], $_FILES['attachment3']['name']);
                                }
                                if (isset($_FILES['attachment4']) && $_FILES['attachment4']['error'] == UPLOAD_ERR_OK) {
                                    $mail->AddAttachment($_FILES['attachment4']['tmp_name'], $_FILES['attachment4']['name']);
                                }
                                if (isset($_FILES['attachment5']) && $_FILES['attachment5']['error'] == UPLOAD_ERR_OK) {
                                    $mail->AddAttachment($_FILES['attachment5']['tmp_name'], $_FILES['attachment5']['name']);
                                }
				foreach($_FILES as $userfile){
					$tmp_name = $userfile['tmp_name'];
					$type = $userfile['type'];
					$name = $userfile['name'];
					$size = $userfile['size'];
					$strFileType = strrev(substr(strrev($name),0,4));
					if (file_exists($tmp_name)){
						if(is_uploaded_file($tmp_name)){
							function rand_string( $length ) {
								$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
								$size = strlen( $chars );
								for( $i = 0; $i < $length; $i++ ) {
									$str .= $chars[ rand( 0, $size - 1 ) ];
								}
								return $str;
							}
							$random_string = rand_string(20);
							$NewUpload = $random_string.$strFileType;
							$NewFileNameforDB = $random_string.$strFileType.'['.$name.']'.','; 
							$uploaddir = 'upload/';
							move_uploaded_file($tmp_name, $uploaddir.$NewUpload);
							if ($filename == "") {
								$filename = mysql_real_escape_string($random_string.$strFileType.'['.$name.']');
							} else {
								$filename = mysql_real_escape_string($filename.','.$random_string.$strFileType.'['.$name.']');
							}
						}
					}
				}
				if(!$mail->Send()) {
                                        echo '<div style="color:red;" align="right">Reply failed to be sent...</div><br/>';
                                } else {
                                   echo '<div style="color:red;" align="right">Message has been successfully sent. </div><br/>';
                                   }	
                            } else { 
                            	echo '<b>Validation Error(s):</b><br /><br />';
                                foreach ($errors as $msg) { 
                                	echo '<div style="color:red;"> -' . $msg . '</div><br />';
                                }        
                            }
                        }
Last edited by cjkeane on Thu Oct 23, 2014 1:34 pm, edited 1 time in total.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP problem with for each $_FILES

Post by requinix »

AddAttachment() doesn't read the file into the email. It just keeps track of filenames. Later in your code you do a move_uploaded_file() on everything so when the email is being sent none of the attachments will work. Not having a body could also be a symptom of this problem.

You can
a) Add the attachments using the temporary filenames, send the email, and then move the files
b) Move the files, then add the attachments using the new filenames and send the email
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP problem with for each $_FILES

Post by cjkeane »

Thanks for your swift reply. I moved the foreach($_FILES as $userfile) like so, but the issue still remains. Did I move the coding correctly? Thanks.

Code: Select all

           if(!$mail->Send()) {
                  echo '<div style="color:red;" align="right">Reply failed to be sent...</div><br/>';
           } else {
		foreach($_FILES as $userfile){
			$tmp_name = $userfile['tmp_name'];
			$type = $userfile['type'];
			$name = $userfile['name'];
			$size = $userfile['size'];
			$strFileType = strrev(substr(strrev($name),0,4));
			if (file_exists($tmp_name)){
				if(is_uploaded_file($tmp_name)){
					function rand_string( $length ) {
						$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
						$size = strlen( $chars );
						for( $i = 0; $i < $length; $i++ ) {
							$str .= $chars[ rand( 0, $size - 1 ) ];
						}
						return $str;
					}
					$random_string = rand_string(20);
					$NewUpload = $random_string.$strFileType;
					$NewFileNameforDB = $random_string.$strFileType.'['.$name.']'.','; 
					$uploaddir = 'upload/';
					move_uploaded_file($tmp_name, $uploaddir.$NewUpload);
					if ($filename == "") {
						$filename = mysql_real_escape_string($random_string.$strFileType.'['.$name.']');
					} else {
						$filename = mysql_real_escape_string($filename.','.$random_string.$strFileType.'['.$name.']');
					}
				}
			}
		}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: PHP problem with for each $_FILES

Post by requinix »

And if you comment out that foreach again, even though you've moved it?
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP problem with for each $_FILES

Post by cjkeane »

if i comment out/remove that whole foreach section, then the email sends with attachment(s) and content in the content area.
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP problem with for each $_FILES

Post by cjkeane »

I've tried rewriting the code like so, so that the $mail->AddAttachment($tmp_name); occurs before the move, but that doesn't work either

REVISION: I'm almost there. I managed to get it working as per one of your suggestions but not quite the way I need it to. Right now, emails are send and received correctly, meaning all attachments are received and the body of the message in the email displays intact as well. My only issue is that after I move the attachments to the folder, each attachment is uniquely renamed. I would much prefer that the attachments be emailed with their original names, but after the email is sent, move and rename the attachments. Any further help would be appreciated. Thanks.

Code: Select all

       foreach($_FILES as $userfile){
		$tmp_name = $userfile['tmp_name'];
		$type = $userfile['type'];
		$name = $userfile['name'];
		$size = $userfile['size'];
		$strFileType = strrev(substr(strrev($name),0,4));
		if(is_uploaded_file($tmp_name)){
			$random_string = rand_string(20);
			$NewUpload = $random_string.$strFileType;
			$uploaddir = 'upload/';
			move_uploaded_file($tmp_name, $uploaddir.$NewUpload);
			$fullpath = $uploaddir . $NewUpload;
			$mail->addattachment($fullpath); 
			if ($filename == "") {
				$filename = mysql_real_escape_string($random_string.$strFileType.'['.$name.']');
			} else {
				$filename = mysql_real_escape_string($filename.','.$random_string.$strFileType.'['.$name.']');
			}
                 }
	}            
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: PHP problem with for each $_FILES

Post by Weirdan »

just use the second argument of addAttachment() method:

Code: Select all

$mail->addAttachment($fullpath, $name);
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP problem with for each $_FILES

Post by cjkeane »

perfect! that works. thank you!
Post Reply