Jump to content

Trouble attaching multiple files


squigs

Recommended Posts

Hello I'm working on a form with multiple file attachments. I have a couple questions regarding it.

 

<?php
$uploadArray= array();
$uploadArray[] = ($_POST['uploaded_file[]']);
?>

 

If I had multiple file inputs sharing the name "uploaded_file[]" would this be a proper way to handle it? or would I be better off assigning multiple names to the inputs?

 

I will leave it at that for now but have more questions to come!

 

Thanks!

Link to comment
Share on other sites

Here a form for the user to select how many files to upload.

 

The name file is now  array() file[]

 

Also your need to add another submit to get the info processed.

 


<html>
<body>

<form action=" " method="post" enctype="multipart/form-data">

How many files to upload?

<select name="number">

<?php for($i=1; $i<11; $i++){?>

<option><?php echo $i; ?></option>

<?php

}?>

</select> <input type="submit" name="submit1" value="Submit" />

<?php 

if($_POST['submit1']){

$number=$_POST['number'];

for($n=0; $n<$number; $n++){

?>
<br><br>
<input type='file' name='file[]'  />
<br>
<?php } }?>

</form>
</body>
</html>

Link to comment
Share on other sites

little update your getting there?

 



<?php

if($_POST['submit2']){

// Get the array of file[] from the form and process it.

$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
      }
    }
  }
else
  {
  echo "Invalid file";
  }
   }
?> 

<html>
<body>

<form action=" " method="post" enctype="multipart/form-data">

How many files to upload?

<select name="number">

<?php for($i=1; $i<11; $i++){?>

<option><?php echo $i; ?></option>

<?php

}?>

</select> <input type="submit" name="submit1" value="Submit" />

<?php 

if($_POST['submit1']){

$number=$_POST['number'];

for($n=0; $n<$number; $n++){

?>
<br><br>
<input type='file' name='file[]'  />
<br>
<?php } }?>

<br><br>

Know upload all the files selected!

<input type="submit" name="submit2" value="Submit" />

</form>
</body>
</html> 

Link to comment
Share on other sites

Thank s for your response. It clarifies how to handle the array.

 

What I am trying to do is accomplish it without the options drop down by using a little jquery. For the end result I would like it to function just like the one on phpfreaks below the message I'm writing.

 

This is my client-side so far.  http://jsfiddle.net/schwiegler/q2v42/2/

 

A question regarding the code you have given as an example -

<?php
($_FILES["file"]["type"] == "image/jpeg")
?>

 

why do we write image/jpeg rather than just jpeg?

 

Once again thanks for your responses

I will continue to play around and hope it can be further adapted to my usage

 

cheers

Link to comment
Share on other sites

A question regarding the code you have given as an example

 

The form processing code that was posted should not be used, ever. Not only does it not address how to process the array of multiple uploaded files, it is derived from the w3schools site and since it tests for upload errors AFTER it has tried to use the uploaded file information, it will never correctly report upload errors.

 

See example #3 at the following link for how you would loop over the resulting array of uploaded files, testing for upload errors first, then only using the uploaded file information when there were not any upload errors - http://us.php.net/manual/en/features.file-upload.post-method.php You would insert your validation logic right before the move_uploaded_file statement in the php.net example code.

Link to comment
Share on other sites

After working at it a little more my script appears to be working (somewhat)..

 

my form is being sent but with only one attachment. It may be worth noting I am using Mail_mime for this script.

I am not sure if I have overlooked something simple but I will post the code below as well as re-post the link to my jsfiddle which will demo the feel I want to achieve. http://jsfiddle.net/schwiegler/q2v42/2/

 

<?php
//Settings 
$max_allowed_file_size = 8000*1024; // size in KB 
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "doc", "docx", "pdf", "zip", "rar");
$upload_folder = './uploads/'; //<-- this folder must be writeable
$your_email = 'blah@blah.com';//<<--  email address

$errors ='';

if(isset($_POST['submit']))
{

///------------Do Validations-------------	
if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['project_name'])||empty($_POST['project_location'])||empty($_POST['message']))
{
	$errors .= "\n Please note that all fields are required!. ";	
}
if(IsInjected($visitor_email))
{
	$errors .= "\n Bad email value!";
}

//------ Validate the file size and extension -----
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
    if ($error == UPLOAD_ERR_OK) {
        $tmp_name = $_FILES["uploaded_file"]["tmp_name"][$key];
        $name_of_uploaded_file =($_FILES["uploaded_file"]["name"][$key]);
	$type_of_uploaded_file = substr($name_of_uploaded_file, 
						strrpos($name_of_uploaded_file, '.') + 1);
	$size_of_uploaded_file = $_FILES["uploaded_file"]["size"][$key];
	$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;


    if($size_of_uploaded_file > $max_allowed_file_size ) 
{
	$errors .= "\n Size of file should be less than $max_allowed_file_size";
}

$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++) 
{ 
	if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
	{
		$allowed_ext = true;		
	}
}

if(!$allowed_ext)
{
	$errors .= "\n The uploaded file is not supported file type. ".
	" Only the following file types are supported: ".implode(',',$allowed_extensions);
}

				//copy the temp. uploaded file to uploads folder


	if(is_uploaded_file($tmp_name))
	{
	    if(!copy($tmp_name,$path_of_uploaded_file))
	    {
	    	$errors .= '\n error while copying the uploaded file';
	    }
	}
}
}
//send the email 
if(empty($errors))
{	
	//send the email
	$name = $_POST['name'];
	$visitor_email = $_POST['email'];
	$user_message = $_POST['message'];
	$to = $your_email;
	$subject="New form submission";
	$from = $visitor_email;
	$text = "From:$name \n Comments:$user_message";

	$message = new Mail_mime(); 
	$message->setTXTBody($text);

	$message->addAttachment($path_of_uploaded_file); //attach file (could the problem be with this?)

                $body = $message->get();
	$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
	$headers = $message->headers($extraheaders);
	$mail = Mail::factory("mail");
	$mail->send($to, $headers, $body);
	//redirect to 'thank-you page
}
}
?>

 

Also worth noting is that multiple files ARE being uploaded to correct folder destination

 

Thanks again!

Link to comment
Share on other sites

You're only getting 1 attachment because you're overwriting the 1st attachment.

 

Inside your foreach loop where you check the attachments, you have this code:

 

$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;

 

That means, for the first attachment, $path_of_uploaded_file is set, and then the loop starts over for the second attachment. The second attachment overwrites the position of the first:

 

$path_of_uploaded_file = $upload_folder . $name_of_uploaded_file; // this runs for the 2nd attachment, overwriting the path to the 1st attachment

 

and thus you only get 1 attachment.

 

One solution would be to use an array:

 

$path_of_uploaded_file[] = $upload_folder . $name_of_uploaded_file

 

Then use another foreach loop to attach the uploads:

 

foreach ($path_of_uploaded_file as $value) {
   $message->addAttachment($value);
}

Link to comment
Share on other sites

One solution would be to use an array:

$path_of_uploaded_file[] = $upload_folder . $name_of_uploaded_file

Thank you for pointing that out! In this instance do I also have to remove the created array from the loop as well?

Link to comment
Share on other sites

Thank you for pointing that out! In this instance do I also have to remove the created array from the loop as well?

 

I'm not quite sure what you mean by "remove the created array from the loop."

 

If you make the two changes I listed above (save the path to the attachment to an array, and then use a loop to load each of the attachments to the e-mail using the array you made in the 1st change) you should be able to e-mail multiple attachments at the same time.

 

Erm, one of my codes above is missing a semi-colon, must have hit delete 1 too many times. Correction is here:

 

$path_of_uploaded_file[] = $upload_folder . $name_of_uploaded_file;

 

Link to comment
Share on other sites

Thank you for pointing that out! In this instance do I also have to remove the created array from the loop as well?

 

I'm not quite sure what you mean by "remove the created array from the loop."

 

sorry about that, I made the changes you suggested but am still having the same result. I know you are on the right track I just may have to tweak a bit more...

 

would I also have to change

if(!copy($tmp_name,$path_of_uploaded_file))
//to
if(!copy($tmp_name,$path_of_uploaded_file[]))
//??

 

Link to comment
Share on other sites

Ahh, yes, you'll need to make a change here too:

 

foreach ($path_of_uploaded_file as $value) {
   if(!copy($tmp_name,$value))
   {
      $errors .= '\n error while copying uploaded file ';
   }
}
reset($path_of_uploaded_file);

 

This will print errors for each uploaded file that couldn't be copied.

Link to comment
Share on other sites

Ahh, yes, you'll need to make a change here too:

 

This will print errors for each uploaded file that couldn't be copied.

 

Than you for your help however I must still be overlooking something! having the same result as always - a one file attachment.

 

will keep poking away!

Link to comment
Share on other sites

Than you for your help however I must still be overlooking something! having the same result as always - a one file attachment.

 

will keep poking away!

 

Can you post your updated code, there's been quite a few edits so lets make sure everything is in there correctly.

Link to comment
Share on other sites

//Settings 
$max_allowed_file_size = 8000*1024; // size in KB 
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "doc", "docx", "pdf", "zip", "rar");
$upload_folder = './uploads/'; //<-- this folder must be writeable
$your_email =yup@yup.com//<<--  email address
$errors ='';


//--------Where to include for progress bar?--------
//	$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
//	var_dump($_SESSION[$key]);

///------------Do Validations-------------
if(isset($_POST['submit']))
{
if(empty($_POST['name'])
||empty($_POST['email'])
||empty($_POST['project_name'])
||empty($_POST['project_location'])
||empty($_POST['message']))
{
	$errors .= "\n Please note that all fields are required!. ";	
}
if(IsInjected($visitor_email))
{
	$errors .= "\n Bad email value!";
}

//------ Validate the file size and extension -----
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
    
if ($error == UPLOAD_ERR_OK) {	
        $tmp_name = $_FILES["uploaded_file"]["tmp_name"][$key];
        $name_of_uploaded_file =($_FILES["uploaded_file"]["name"][$key]);
	$type_of_uploaded_file = substr($name_of_uploaded_file, 
						     strrpos($name_of_uploaded_file, '.') + 1);
	$size_of_uploaded_file = $_FILES["uploaded_file"]["size"][$key];	

	$path_of_uploaded_file[] = $upload_folder . $name_of_uploaded_file;//this was a change

    if($size_of_uploaded_file > $max_allowed_file_size ) 
{
	$errors .= "\n Size of file should be less than $max_allowed_file_size";
}

$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++) 
{ 
	if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
	{
		$allowed_ext = true;		
	}
}

if(!$allowed_ext)
{
	$errors .= "\n The uploaded file is not supported file type. ".
	" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
}

//copy the temp. uploaded file to uploads folder	
	if(is_uploaded_file($tmp_name))	{
		if(!copy($tmp_name,$path_of_uploaded_file))//had to leave original because $value not yet set...
	    {
	    	$errors .= '\n error while copying the uploaded file';
	    }

}

}
//send the email 
if(empty($errors))
{	
	//send the email
	$name = $_POST['name'];
	$visitor_email = $_POST['email'];
	$user_message = $_POST['message'];
	$to = $your_email;
	$subject="New form submission";
	$from = $visitor_email;
	$text = "From:$name \n Comments:$user_message";
	$message = new Mail_mime(); 
	$message->setTXTBody($text);

	foreach ($path_of_uploaded_file as $value) {
        $message->addAttachment($value);
		}

	$body = $message->get();
	$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
	$headers = $message->headers($extraheaders);
	$mail = Mail::factory("mail");
	$mail->send($to, $headers, $body);
	//redirect to 'thank-you page
}
}

Link to comment
Share on other sites

Okay, I see the problem, change this:

 

$path_of_uploaded_file[] = $upload_folder . $name_of_uploaded_file;

 

To:

 

$temp_path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;

 

Then change:

 

if(!copy($tmp_name,$path_of_uploaded_file))//had to leave original because $value not yet set...
	    {
	    	$errors .= '\n error while copying the uploaded file';
	    }

 

To:

 

if(!copy($tmp_name,$temp_path_of_uploaded_file))//had to leave original because $value not yet set...
	    {
	    	$errors .= '\n error while copying the uploaded file';
	    }
$path_of_uploaded_file[] = $temp_path_of_uploaded_file

 

Sorry about that, let me know if that works.  :)

Link to comment
Share on other sites

Sorry about that, let me know if that works.  :)

Ha! don't apologize you've taken me further in 20 minutes then I have in 4 hours! so I now get three attachments but they are all named array and are empty... :) I'm very close I can feel it!

Link to comment
Share on other sites

Can you copy your current code again?

//Settings 
$max_allowed_file_size = 8000*1024; // size in KB 
$allowed_extensions = array("jpg", "jpeg", "gif", "bmp", "doc", "docx", "pdf", "zip", "rar");
$upload_folder = 'uploads/'; //<-- this folder must be writeable
$your_email = 'yup@yup.com';//<<--  email address
$errors ='';


//--------Where to include for progress bar?--------
//	$key = ini_get("session.upload_progress.prefix") . $_POST[ini_get("session.upload_progress.name")];
//	var_dump($_SESSION[$key]);

///------------Do Validations-------------
if(isset($_POST['submit']))
{
if(empty($_POST['name'])
||empty($_POST['email'])
||empty($_POST['project_name'])
||empty($_POST['project_location'])
||empty($_POST['message']))
{
	$errors .= "\n Please note that all fields are required!. ";	
}
if(IsInjected($visitor_email))
{
	$errors .= "\n Bad email value!";
}

//------ Validate the file size and extension -----
foreach ($_FILES["uploaded_file"]["error"] as $key => $error) {
    
if ($error == UPLOAD_ERR_OK) {	
        $tmp_name = $_FILES["uploaded_file"]["tmp_name"][$key];
        $name_of_uploaded_file =($_FILES["uploaded_file"]["name"][$key]);
	$type_of_uploaded_file = substr($name_of_uploaded_file, 
						     strrpos($name_of_uploaded_file, '.') + 1);
	$size_of_uploaded_file = $_FILES["uploaded_file"]["size"][$key];			
	$temp_path_of_uploaded_file[] = $upload_folder . $name_of_uploaded_file;//this was a change

    if($size_of_uploaded_file > $max_allowed_file_size ) 
{
	$errors .= "\n Size of file should be less than $max_allowed_file_size";
}	
$allowed_ext = false;
for($i=0; $i<sizeof($allowed_extensions); $i++) 
{ 
	if(strcasecmp($allowed_extensions[$i],$type_of_uploaded_file) == 0)
	{
		$allowed_ext = true;		
	}
}

if(!$allowed_ext)
{
	$errors .= "\n The uploaded file is not supported file type. ".
	" Only the following file types are supported: ".implode(',',$allowed_extensions);
}
$path_of_uploaded_file[] = $temp_path_of_uploaded_file;
//copy the temp. uploaded file to uploads folder	
	if(is_uploaded_file($tmp_name))	{
		if(!copy($tmp_name,$temp_path_of_uploaded_file))//had to leave original because $value not yet set...
	    {
	    	$errors .= '\n error while copying the uploaded file';
	    }

}
}
}
//send the email 
if(empty($errors))
{	
	//send the email
	$name = $_POST['name'];
	$visitor_email = $_POST['email'];
	$user_message = $_POST['message'];
	$to = $your_email;
	$subject="New form submission";
	$from = $visitor_email;
	$text = "From:$name \n Comments:$user_message";
	$message = new Mail_mime(); 
	$message->setTXTBody($text);

	foreach ($path_of_uploaded_file as $value) {
        $message->addAttachment($value);
		}

	$body = $message->get();
	$extraheaders = array("From"=>$from, "Subject"=>$subject,"Reply-To"=>$visitor_email);
	$headers = $message->headers($extraheaders);
	$mail = Mail::factory("mail");
	$mail->send($to, $headers, $body);
	//redirect to 'thank-you page
}
}

Link to comment
Share on other sites

You missed a little bit of my code when you copied. Your code is:

 

if(!copy($tmp_name,$temp_path_of_uploaded_file))//had to leave original because $value not yet set...
          {
             $errors .= '\n error while copying the uploaded file';
          }

 

It needs to be:

 

if(!copy($tmp_name,$temp_path_of_uploaded_file))//had to leave original because $value not yet set...
	    {
	    	$errors .= '\n error while copying the uploaded file';
	    }
$path_of_uploaded_file[] = $temp_path_of_uploaded_file;

 

You're missing $path_of_uploaded_file[] = $temp_path_of_uploaded_file;.

Link to comment
Share on other sites

Oh, I see, the problem was here, actually:

 

$temp_path_of_uploaded_file[] = $upload_folder . $name_of_uploaded_file;

 

This should be:

 

$temp_path_of_uploaded_file = $upload_folder . $name_of_uploaded_file;

 

That does it!! Thank you for all of your help!! The problem always seems to be in the details doesn't it ;)

This script is now working like a charm. Now to add a progress bar to it..

But that is one for another post I think...

Cheers buddy!

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.