Solved

Multiple File Upload Problem PHP

Posted on 2011-09-26
26
414 Views
Last Modified: 2012-05-12
Hello,

I'm trying to upload multiple files simultaneously using PHP, but i dont know why its not working. below is code :

<form action="" method="post" enctype="multipart/form-data">
  Send these files:<br />
  <input name="name[]" type="file" /><br />
  <input name="pictures[]" type="file" /><br />
  <input type="submit" value="Send files" />
</form>
 
<?php
   $target = $_POST['path'];
   $fileone = $_FILES['name']['name'];
   $filetwo = $_FILES['picture']['name'];
    $Tdate = date('dFY');

   $path= "/home/path/images/".basename($_FILES['upload']['name']) ;
if(move_uploaded_file($_FILES['uploaded']['tmp_name'],$destfile))
            {
 
                  echo "copied succesfully to ".$destfile."<br/>";
            }
              else
            {
                  echo "failed to copy<br/>";
            }


The problem im facing is if i browse and try to upload both files togather then the script is just going in loop and doing nothing, however if I try to upload any one of them, then it works!

Do you think it could be some problems with php.ini settings or maybe firewall on server? I'm using LAMP with apf firewall.

Thanks,
0
Comment
Question by:david_php
  • 10
  • 7
  • 3
  • +2
26 Comments
 
LVL 9

Expert Comment

by:oheil
Comment Utility
The first I see is a typo:

$filetwo = $_FILES['picture']['name'];

should be

$filetwo = $_FILES['pictures']['name'];

but I guess thats not the real problem and investigate further...

Oli
0
 
LVL 9

Expert Comment

by:oheil
Comment Utility
Your code seems to be a little bit ... wrong, looking at the documentation of php it should be

$_FILES['userfile']['name'] and not 'upload'

for example.
But I may be wrong as I just looked into the php doc:
http://www.php.net/manual/en/features.file-upload.multiple.php

oli
0
 

Author Comment

by:david_php
Comment Utility
well, thats not a big deal... but the problem is i don't get response from server at all when I post multiple files!!
0
 
LVL 3

Expert Comment

by:FrankoH
Comment Utility
It sounds like your uploading data greater than the maximum POST size configured on your hosting.

Some hosts / default setups have this set at 2Mb, so if the combined filesize of the images is greater, then the script would just fail to work and an msg would be dumped in the error log.

Try printing the post size i.e. echo ini_get('post_max_size');
That will tell you the maximum amount of data you can post. If it is too low you will need to update your hosting php.ini config file with a greater POST size.
0
 
LVL 9

Expert Comment

by:oheil
Comment Utility
What are the php.ini values of

upload_max_filesize
post_max_size
max_execution_time

And set
error_reporting(E_ALL);
ini_set("display_errors", 1);

What is written into php.log?

Print the value of
$_FILES['uploaded']['tmp_name']
before calling move_uploaded_file
(that means print the first parameter of move_uploaded_file)

Oli


0
 

Author Comment

by:david_php
Comment Utility
max_execution_time => 0 => 0

max_file_uploads => 30 => 30

post_max_size => 16M => 16M

upload_max_filesize => 32M => 32M
0
 
LVL 9

Expert Comment

by:oheil
Comment Utility
If your files together are smaller than 16M than thats not the problem.

But set post_max_size to 32M.
max_execution_time should be set to some value in seconds to prevent that scripts run forever blocking the server.

So far no hint to the solution.
Have you tried to upload rather small files? Like two 1KByte files just for testing?

Oli
0
 

Author Comment

by:david_php
Comment Utility
yes it didnt work though. :(
0
 
LVL 9

Expert Comment

by:oheil
Comment Utility
Try the following code:
<form action="" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="file" name="pictures[]" />
<input type="submit" value="Send" />
</p>
</form>
<?php
//places files into same dir as form resides
foreach ($_FILES["pictures"]["error"] as $key => $error) {
   if ($error == UPLOAD_ERR_OK) {
       echo"$error_codes[$error]";
       move_uploaded_file(
         $_FILES["pictures"]["tmp_name"][$key],
         $_FILES["pictures"]["name"][$key]
       ) or die("Problems with upload");
   }
}

Open in new window


Shamelessly stolen from here:
http://www.php.net/manual/en/features.file-upload.multiple.php
Thanx to Bob Doe.

Oli
0
 

Author Comment

by:david_php
Comment Utility
hey

still nothing, same problem. This same code working fine in my localhost but its not working on server, so i think something is wrong with maybe apache,php settings?
0
 
LVL 9

Expert Comment

by:oheil
Comment Utility
does
phpinfo();
work?

Put

phpinfo();
exit();

at the first lines into your php script and try.

Oli
0
 

Author Comment

by:david_php
Comment Utility
yes it does.. even the script works when I try to upload just one image at a time.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 9

Accepted Solution

by:
oheil earned 500 total points
Comment Utility
I tested it now on my apache server and voila, same problem!

The only solution I have now is a workaround:

print("<form action=\"\" method=\"post\" enctype=\"multipart/form-data\">");
print("<p>Pictures:");
print("<input type=\"file\" name=\"picture1\" />");
print("<input type=\"file\" name=\"picture2\" />");
print("<input type=\"submit\" value=\"Send\" />");
print("</p>");
print("</form>");
foreach( $_FILES as $name => $file_details ) {
        print( $_FILES[$name]["tmp_name"]."\n");
        print( $_FILES[$name]["name"]."\n");
        if( is_uploaded_file($_FILES[$name]["tmp_name"]) ) {
                rename( $_FILES[$name]["tmp_name"], $_FILES[$name]["name"] );
        }
}

Open in new window


move_uploaded_file does not work properly on my system. I believe that the check if the uploaded temporary files are regular fails of some reason I can not find out.

Also the arrays in the form needed to be removed, reason unknown (but maybe not necessary, it was the first thing I changed).

The above code snippet works and renames the tmp files to its original names in directory /tmp/
Any other writeable target directory works also, I checked.

To analyze the $_FILES array I had a
print_r($_FILES);
before the foreach line. You may also check, e.g. for error codes or file size.

Oli

0
 
LVL 9

Expert Comment

by:oheil
Comment Utility
Actually the code does not target directory /tmp , sorry, copy&paste to fast.
Line 12 was originally:
rename( $_FILES[$name]["tmp_name"], "/tmp/".$_FILES[$name]["name"] );

Oli
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Here is a teaching example of how to upload multiple files.  You can try it and see if it works for you.
http://www.laprbass.com/RAY_upload_example.php
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES YOU MUST UNDERSTAND TO UPLOAD FILES
// http://php.net/manual/en/features.file-upload.php
// http://php.net/manual/en/features.file-upload.common-pitfalls.php
// http://php.net/manual/en/function.move-uploaded-file.php


// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'RAY_junk';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8192000';

// ESTABLISH THE MAXIMUM NUMBER OF FILES WE CAN UPLOAD
$nf = 3;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE CAN ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
)
;

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;




// IF THERE IS NOTHING IN $_POST, PUT UP THE FORM FOR INPUT
if (empty($_POST))
{
    ?>
    <h2>Upload <?php echo $nf; ?> file(s)</h2>

    <!--
        SOME THINGS TO NOTE ABOUT THIS FORM...
        ENCTYPE IN THE HTML <FORM> STATEMENT
        MAX_FILE_SIZE MUST PRECEDE THE FILE INPUT FIELD
        INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN $_FILES ARRAY
        ABSENCE OF ACTION= ATTRIBUTE IN FORM TAG CAUSES POST TO SAME SCRIPT
    -->

    <form name="UploadForm" enctype="multipart/form-data" method="post">
    <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size; ?>" />
    <p>
    Find the file(s) you want to upload and click the "Upload" button below.
    </p>

    <?php // CREATE INPUT STATEMENTS FOR UP TO $n FILE NAMES
    for ($n = 0; $n < $nf; $n++)
    {
        echo "<input name=\"userfile$n\" type=\"file\" size=\"80\" /><br/>\n";
    }
    ?>

    <br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files.
    <input type="submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT



// WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
else
{
    // THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: File Upload</h2>\n";

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH
    //    echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>\n";

    // ITERATE OVER THE CONTENTS OF $_FILES
    foreach ($_FILES as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code    = $my_uploaded_file["error"];
        if ($error_code == 4) continue;

        // SYNTHESIZE THE NEW FILE NAME
        $f_type    = trim(strtolower(end    (explode( '.', basename($my_uploaded_file['name'] )))));
        $f_name    = trim(strtolower(current(explode( '.', basename($my_uploaded_file['name'] )))));
        $my_new_file = getcwd() . '/' . $uploads . '/' . $f_name . '.' . $f_type;
        $my_file     =                  $uploads . '/' . $f_name . '.' . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts)) die("Sorry, $f_type files not allowed");

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            die("Sorry, Upload Error Code: $error_code: $error_message");
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_new_file))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file</i></b> already exists.\n";

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    echo "<br/><strong>Attempted Backup Failed!</strong>\n";
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten.\n"; }
        if ($upload_success == 1) { echo "<br/><strong>$my_file</strong> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><strong>It was NOT overwritten.</strong>\n"; }
        if ($upload_success < 0)  { echo "<br/><strong>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</strong>\n"; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded.\n";
            if (!chmod ($my_new_file, 0755))
            {
                echo "<br/>chmod(0755) FAILED: fileperms() = ";
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo "<br/><a href=\"$my_file\">See the file $my_file</a>\n";
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
}

Open in new window

0
 
LVL 6

Expert Comment

by:neorush
Comment Utility
If have experienced some problems with using name="fieldname[]" with the way browsers post this stuff.
I would suggest trying something like this:

<?php
if(isset($_POST['pictures_total'])){
	for($i=0; $i<$_POST['pictures_total']; $i++){
		if(isset($_FILES['picture_'.$i]) && is_uploaded_file($_FILES["picture_".$i]['tmp_name'])){
			echo 'File "'.$_FILES["picture_".$i]['name'].'" uploaded ok to "'.$_FILES["picture_".$i]['tmp_name'].'" with size: '.filesize($_FILES["picture_".$i]['tmp_name']).'<br />';
		}
		else {
			echo 'No valid upload found picture for '.$i.'<br />';
		}
	}
}
?>
<form action="<?=$_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
<p>Pictures:
<input type="file" name="picture_0" />
<input type="file" name="picture_1" />
<input type="file" name="picture_2" />
<input type="hidden" name="pictures_total" value="3" />
<input type="submit" value="Send" />
</p>
</form>

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
problems with using name="fieldname[]" ??

I have never seen a problem with that.  It is standard array notation and is used all the time.  If you can show us an example of a problem with GET or POST array notation I would be glad to help you find the solution.  I expect the browser makers would want to know about it, too.
http://php.net/manual/en/faq.html.php
http://php.net/manual/en/faq.html.php#faq.html.arrays
0
 
LVL 6

Expert Comment

by:neorush
Comment Utility
I should have been more specific about this, I have experienced problems with browser addons / extensions that attempt to read / autofill fields.  A year or so ago there was a problem a customer was having that was almost the exact same problem, (could only upload one field at a time) it worked for everyone except him.  There was some buggy add-on (I'll see if I can find the email to post what it was) that when it tried to read fields in array notation it would load all three into the DOM as the same field. Thus only one field would ever be uploaded.  Ever since then I have avoided using array notation, since with good scripting there is really no reason to use it anyway.  That's why I suggested trying this without array notation, all though it is unlikely this is the issue.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
@neorush: I disagree that avoiding array notation is "good scripting."  Arrays exist to handle the logical constructs that arise when a programmer says to himself, "I have more than one of these things and I need to handle them all the same way.  What should I do with them?"  If you don't use an array of length N, you wind up creating N variables.  And in computer science we learn any programming that results in a proliferation of variables introduces more points for potential errors.

If there is an add-on that is causing array notation to fail, the right thing to do is fix the add-on.

You can test the upload script I posted here to see how it works.  Copy it and install it on your server, or try it on my server.  It's on my server at this URL.
http://www.laprbass.com/RAY_upload_example.php
0
 
LVL 6

Expert Comment

by:neorush
Comment Utility
@ray regardless, the solution I posted is a potential pitfall for the OP.  This is why it was posted.  The solution I posted does not use javascript / DOM arrays, but it does use PHP arrays to avoid the problem you refer to with creating N variables.  Take a look at what high usage sites e.g.  Gmail's multiple file upload scripts, they do not use array notation, partly because of reliability interoperability between different clients. In a perfect world we absolutely should fix / remove the add-on.  In the real world people just want it work without having to figure out why.  It would still be a good idea for OP to try this solution, and yours, to see if it might be the issue.
0
 

Author Comment

by:david_php
Comment Utility
thank you guys, thanks for your help
0
 

Author Comment

by:david_php
Comment Utility
I've requested that this question be closed as follows:

Accepted answer: 0 points for david_php's comment http:/Q_27342965.html#36903292

for the following reason:

thanks
0
 
LVL 9

Expert Comment

by:oheil
Comment Utility
Here are some potential solutions to the problem.
david_php should either value the effort or give a statement, why our effort is not worth the points.

Oli
0
 
LVL 9

Expert Comment

by:oheil
Comment Utility

In my point of view I would say:
#3 accept http:#36709978
because its tested and working code and should solve the problems at first.

If david_php is the opinion, that a more theoretical view is needed, he may split the points after testing the other comments after http:#36709978

0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
This article discusses how to create an extensible mechanism for linked drop downs.
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now