PHP inserting mail attachment names in db

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 inserting mail attachment names in db

Post by cjkeane »

Hi everyone,

i have a slight issue when sending email with php. when i echo file attachment names outside my foreach loop only the last filename is listed. when i echo the filenames within the foreach loop, then each filename is listed, however when i insert the filename in the db, only the last filename is inserted. i need all filenames to be inserted in the db in one field like so:
filename1.ext,filename2.ext etc. i'm not sure how to accomplish that. does anyone have any ideas? thanks.

Code: Select all

<php
if(isset($_POST['Send'])){ 
	
		$to = $_POST['emailcc'];
		$emailcc = $_POST['emailcc'];	
		$emailbcc = $_POST['emailbcc'];	
                $emailfrom = $_POST['emailfrom'];
		$subject = "RE: " . utf8_decode($Subject);
		$returnpath = explode("<", $from);
		$returnpath = str_replace(">", "", $returnpath['1']);
		$body .= utf8_decode($_POST['body']);

                $now = md5(date('r', time()));				
		$priority = "3";
		$headers = "From: " . $emailfrom ."\n";
		$headers .= "Cc: " . $emailcc ."\n";
		$headers .= "Bcc: " . $emailbcc ."\n";
		$headers .= "Reply-To: $emailfrom\n";
		$headers .= "X-Sender: <$emailfrom>\n";
		$headers .= "X-Mailer: PHP v" . phpversion() . "\n";
		$headers .= "X-Priority: $priority\n"; //1 UrgentMessage, 3 Normal
		
	        $semi_rand = md5(time());
		$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
		$headers .= "MIME-Version: 1.0\n" .  "Content-Type: multipart/mixed;\n" .  " boundary=\"{$mime_boundary}\"";
		$message ="--{$mime_boundary}\n";
		$message.="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
		$message.="Content-Transfer-Encoding: 7bit\n\n";
		$message .= str_replace("\n", "", $body)."\n";
				 		
		function rand_string( $length ) {
			$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
			$size = strlen( $chars );
			for( $i = 0; $i < $length; $i++ ) {
				$str .= $chars[ rand( 0, $size - 1 ) ];
			}
			return $str;
		}

foreach($_FILES as $userfile){
	// store the file information to variables for easier access
	$tmp_name = $userfile['tmp_name'];
	$type = $userfile['type'];
	$name = $userfile['name'];
	$size = $userfile['size'];
		 		  
	$strFileType = strrev(substr(strrev($name),0,4));
		
	if ($strFileType == ".asf") $ContentType = "video/x-ms-asf";
   	if ($strFileType == ".avi") $ContentType = "video/avi";
  	if ($strFileType == ".doc") $ContentType = "application/msword";
	if ($strFileType == ".zip") $ContentType = "application/zip";
	if ($strFileType == ".xls") $ContentType = "application/vnd.ms-excel";
	if ($strFileType == ".gif") $ContentType = "image/gif";
	if ($strFileType == ".jpg" || $strFileType == "jpeg" || $strFileType == ".JPG") $ContentType = "image/jpeg";
	if ($strFileType == ".wav") $ContentType = "audio/wav";
	if ($strFileType == ".mp3") $ContentType = "audio/mpeg3";
	if ($strFileType == ".mpg" || $strFileType == "mpeg")	$ContentType = "video/mpeg";
	if ($strFileType == ".rtf") $ContentType = "application/rtf";
	if ($strFileType == ".htm" || $strFileType == "html")	$ContentType = "text/html";
	if ($strFileType == ".xml") $ContentType = "text/xml";
	if ($strFileType == ".xsl") $ContentType = "text/xsl";
	if ($strFileType == ".css") $ContentType = "text/css";
	if ($strFileType == ".php") $ContentType = "text/php";
	if ($strFileType == ".asp") $ContentType = "text/asp";
	if ($strFileType == ".pdf") $ContentType = "application/pdf";
	if ($strFileType == ".odt") $ContentType = "application/vnd.oasis.opendocument.text";
	if ($strFileType == ".ott") $ContentType = "application/vnd.oasis.opendocument.text-template";
	if ($strFileType == ".sxw") $ContentType = "application/vnd.sun.xml.writer";
	if ($strFileType == ".ods") $ContentType = "application/vnd.oasis.opendocument.spreadsheet";
	if ($strFileType == ".wpd") $ContentType = "application/wordperfect";
		  		
	if (file_exists($tmp_name)){
             if(is_uploaded_file($tmp_name)){
	           $file = fopen($tmp_name,'rb');
 	           $data = fread($file,filesize($tmp_name));
	           move_uploaded_file($tmp_name, $uploaddir.$NewUpload);
	           $random_string = rand_string(20);
	           $NewUpload = $random_string.$strFileType;
	           $NewFileNameforDB = $random_string.$strFileType.'['.$name.']'.','; 
                   echo $NewFileNameforDB; // echo's each filename to be inserted into the db.
		   fclose($file);
 	           $data = chunk_split(base64_encode($data));
	    }
	   
            $message .= "--{$mime_boundary}\n" .
            "Content-Type: {$type};\n" .
            " name=\"{$name}\"\n" .
            "Content-Disposition: attachment;\n" .
            " filename=\"{$fileatt_name}\"\n" .
            "Content-Transfer-Encoding: base64\n\n" .
         $data . "\n\n";
      }
   }

   if (!mail($to,$subject,$message,$headers)) {
	echo '<div style="color:red;" align="right">Reply failed to be sent...</div><br/>';
    } else {
        $uploaddir = 'uploads/';
        $id = $_POST['id'];
	mysql_query("INSERT INTO mail(id, CallDate, CallTime, Sender, EmailTo, EmailCC, EmailBCC, Subject, attachments) 
	VALUES ('$id', CURDATE(), NOW(), '$Sender', '$emailTo', '$emailcc', '$emailbcc', '$Subject', '$attachments')") or die(mysql_error()); 
	

?>
greip
Forum Commoner
Posts: 39
Joined: Tue Aug 23, 2011 8:23 am
Location: Oslo, Norway

Re: PHP inserting mail attachment names in db

Post by greip »

I guess you desire to have all the file names collected in the attachments variable.

In your for-loop use a construct somewhat like this:

Code: Select all

if ( !isset($attachements) ) 
  $attachments = $name;
else
  $attachments .= "," . $name;
PS: This code:

Code: Select all

strrev(substr(strrev($name),0,4))
can be improved by using negative arguments to substr().
Last edited by greip on Mon Aug 29, 2011 7:16 am, edited 1 time in total.
cjkeane
Forum Contributor
Posts: 217
Joined: Fri Jun 11, 2010 1:17 pm

Re: PHP inserting mail attachment names in db

Post by cjkeane »

i was able to collect the attachments together in the $attachments variable, separated by a comma. i used your suggestion as a guide with a slight modification. thanks.
Post Reply