Solved

Multiple upload fields

Posted on 2011-09-05
17
449 Views
Last Modified: 2013-11-11
Hi all,

I am looking at the following code:

<html>
<body>

<form action="upload_file.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

</body>
</html> 

Open in new window


and the php

<?php
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
&& ($_FILES["file"]["size"] < 20000))
  {
  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";
  }
?> 

Open in new window



My question is...How can I get it to work with multiple upload fields..

For example:

<input type="file" name="file" id="file" />
<input type="file" name="file2" id="file2" />
<input type="file" name="file3" id="file3" />

Thanks

0
Comment
Question by:error77
  • 7
  • 5
  • 4
  • +1
17 Comments
 
LVL 40

Expert Comment

by:gurvinder372
Comment Utility
0
 

Author Comment

by:error77
Comment Utility
I would prefar not to have to use a different script as the above is already working ... I just need to be about to have multiple imput files
0
 
LVL 40

Expert Comment

by:gurvinder372
Comment Utility
then i guess you just have to repeat php codes for all file tags, may be you can refactor the method to pass the name of the file field, since you are using name 'file' to get the file object
0
 
LVL 36

Expert Comment

by:Loganathan Natarajan
Comment Utility
0
 

Author Comment

by:error77
Comment Utility
Why won't this work on my code:

<input type="file" name="file" id="file" />
<input type="file" name="file2" id="file2" />
<input type="file" name="file3" id="file3" />

?
0
 
LVL 40

Expert Comment

by:gurvinder372
Comment Utility
because you are only checking the file input with name 'file', you need to execute that code for 'file2' and 'file3' also
0
 

Author Comment

by:error77
Comment Utility
OK, I see it now so if there a way to modify the code so it accepts file1, file2 etc without having to add the same code many times?
0
 
LVL 40

Expert Comment

by:gurvinder372
Comment Utility
See this post #36483333 above
Do you know how to refactor the code into a separate method?
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:error77
Comment Utility
Hi gurvinder372,

No, I don't know how to do that to my code. could you help?
0
 
LVL 40

Expert Comment

by:gurvinder372
Comment Utility
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
Comment Utility
prefar not to have to use a different script as the above is already working...

Actually it is not working, if the requirement is to upload multiple files. This is a teaching example showing how I do it (see lines 20 and 21).  Please read it over and post back with any specific questions, ~Ray
<?php // RAY_upload_example.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// 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
 

Author Comment

by:error77
Comment Utility
Hi Ray,

It's looks very commented and easy to understand so thanks for that.

I need to add this code to an existing project so my question is ... can't I break this code into 2 parts:

1. Form post

2. The upload code

So, that I can have all the form submit code in the same external file and just have the form parts merged with my current project?

Do you know what I mean?

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Sure, I think that is possible.  One script would have the form (the HTML) and it would post to the upload script (the PHP).  Professionally, I like to combine these, but it is quite possible to separate them.
0
 

Author Comment

by:error77
Comment Utility
Would the script work if I leave:

<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>

Open in new window


in the main page and move the rest of the code into another page ... then add to the form: action="theExternalPage.php"  ?
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
It's almost always impossible to answer questions like Would the script work if... because the original script I posted has 183 lines, and the hypothetical script has 5 lines.  Could it be made to work?  Yes, of course, but there would be a great deal more code involved.  Would I do it?  No.

In my professional opinion, nothing is gained, and organization is lost, when a programmer separates the form script from the action script. The two scripts are designed to work together, and separating them just introduces more potential points of failure.  Example of lost organization: Everything up through line 44 is common to the two scripts.  If you separate the scripts, you now will need to replicate these "initialization" statements, and this means you will need to keep track of the code in two separate places.  Professionals would not want to add the risk of confusion that unnecessary complexity might bring.

Anyway, best of luck with it, ~Ray
0
 

Author Comment

by:error77
Comment Utility
My problem is that I posted some code hoping that it could be modified to my needs and I then get a new script which I need to adapt to my already existing project.

The problem is that I cannnot just replace the code ... I need to adapt it too, so that's why I ask the questions about modifing the script.

You script could be the greatest but I need have to break it.

I'll give it a try and get back.

Thanks
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
...I posted some code hoping that it could be modified to my needs...

Sigh.  I understand.  We see a lot of questions here at EE that start with, "How can I make this code do [something different]" and when we provide a teaching example we often get a response that goes something like, "but I want to use my code."  That is why we post the teaching examples, because the posted code does not work, and the teaching examples provide guidance about how to modify the code in such a way that it can be made to work.  We cannot write your code for you -- that is what a paid professional programmer does for a living.  We are just volunteers here who try to help and educate to the best of our ability, given an environment that allows for a written back-and-forth dialog.

If there is anything in the example that you do not understand, or any principles that are unclear, please post back and I will try to help.
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
In this tutorial viewers will learn how to embed an audio file in a webpage using HTML5. Ensure your DOCTYPE declaration is set to HTML5: : The declaration should display (CODE) HTML5 is supported by the most recent versions of all major browsers…
The viewer will learn how to dynamically set the form action using jQuery.

743 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

14 Experts available now in Live!

Get 1:1 Help Now