Link to home
Start Free TrialLog in
Avatar of sammySeltzer
sammySeltzerFlag for United States of America

asked on

Uploading multiple unique files to the server and saving rest of files to the database.

Hi again, mates:

Here is the scenario.

I have 5 different unique files, each of which is a fieldname on the datatabase.

Here is a sample markup:

<form id="form1" name="contacts_form" method="post" action="save.php" enctype="multipart/form-data">
..
..
      <td class="td_input_form"><input type="file" name="item1" size="50"></td>
      <td class="td_input_form"><input type="file" name="item2" size="50"></td>
      <td class="td_input_form"><input type="file" name="item3" size="50"></td>
      <td class="td_input_form"><input type="file" name="item4" size="50"></td>
      <td class="td_input_form"><input type="file" name="item5" size="50"></td>
..
..
</form>

Open in new window


We would like to upload all 5 files to a folder called uploads and then save their filename as well as additional form fields to the database.

I am having issues getting this to work.

 <?php

// Connect to SQL Server database
include("../Connections/Connect.php")

//This is the directory where images will be saved
$target = "uploads";
$target = $target . basename( $_FILES['photo']['name']);

//This gets all the other information from the form

    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];
        if ($file_type!="application/pdf" || $file_type!="image/gif" || $file_type!="image/jpeg") {
         $errors[] 'You can only upload PDFs, JPEGs or GIF files.<br>';
        }
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }   
$name='". ms_escape_string($_POST['nameMember']) ."';
$bandMember='". ms_escape_string($_POST['bandMember']) ."';
$pic1='". ms_escape_string(($_FILES['photo1']['name'])) ."';
$pic2='". ms_escape_string(($_FILES['photo2']['name'])) ."';
$pic3='". ms_escape_string(($_FILES['photo3']['name'])) ."';
$pic4='". ms_escape_string(($_FILES['photo4']['name'])) ."';
$pic5='". ms_escape_string(($_FILES['photo5']['name'])) ."';
$about='". ms_escape_string($_POST['aboutMember'];
$bands='". ms_escape_string($_POST['otherBands']) ."';

//Writes the information to the database
$sql="INSERT INTO tableName (nameMember,bandMember,photo1,photo2,photo3,photo4,photo5,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic1', '$pic2', '$pic3', '$pic4', '$pic5', '$about', '$bands')" ;

$objQuery = sqlsrv_query($conn, $sql);

//Writes the files to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{

//If all is ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded to the directory and records saved to the database";
}
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
sqlsrv_close($conn);
}
?>

Open in new window


Somehow, I have the feeling I am confusing the upload file code with the variables to be inserted into the database. Thank you in advance for your help.
Avatar of Duy Pham
Duy Pham
Flag of Viet Nam image

Look like that DB Column Names (photo1, photo2, ...) were misused instead of input field names (as in your sample markup code:  item1, item2, ...).

In your code, I see that there are at least 4 different names were used:  $_FILES['photo'], $_FILES['files'], $_FILES['uploadedfile'], $_FILES['photo1'], ... So it's kind of confused to know whether you use 5 different Uploaded file names or do multiple file uploads in an array.

You might check out the sample multiple files upload code here: http://php.net/manual/en/features.file-upload.multiple.php
This is my teaching example showing how to upload multiple files. To simplify this process you might want to break it apart into two steps.  The first part of the script would handle the file uploads / stores.  The second part of the script (not included in this example - roll your own) would deal with the data base updates.

<?php // demo/upload_multiple_example.php

/**
 * Demonstrate how to upload multiple files in PHP
 *
 * REQUIRED: Man Page References
 * http://php.net/manual/en/reserved.variables.files.php
 * 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/features.file-upload.multiple.php
 * http://php.net/manual/en/function.move-uploaded-file.php
 *
 * IMPORTANT: If dealing with large files
 * http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
 * http://php.net/manual/en/ini.core.php#ini.post-max-size
 * http://php.net/manual/en/info.configuration.php#ini.max-input-time
 */
error_reporting(E_ALL);

// 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 DESTINATION FOLDER ('uploads' DIRECTORY)
$uploads = 'storage';
if (!is_dir($uploads))
{
    mkdir($uploads);
}

// ESTABLISH THE BIGGEST FILE SIZE WE WILL ACCEPT - ABOUT 8 MB
$max_file_size = 8 * 1024 * 1024;

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

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

// 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 WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
if (!empty($_POST))
{
    echo "<h2>Results: File Upload</h2>" . PHP_EOL;

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

    // 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 = explode('.', basename($my_uploaded_file['name']));
        $f_type = end($f_type);
        $f_type = trim(strtolower($f_type));

        $f_name = explode('.', basename($my_uploaded_file['name']));
        $f_name = current($f_name);
        $f_name = trim(strtolower($f_name));

        $my_new_file
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;
        $my_file
        = $uploads
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts))
        {
            trigger_error("$f_type Not allowed", E_USER_WARNING);
            continue;
        }

        // IF THERE ARE ERRORS
        if ($error_code != 0)
        {
            $error_message = $errors[$error_code];
            trigger_error("Upload error code: $error_code: $error_message", E_USER_WARNING);
            continue;
        }

        // 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." . PHP_EOL;

            // 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\THis');
                $my_bak = $my_new_file . '.' . $now . '.bak';
                if (!copy($my_new_file, $my_bak))
                {
                    trigger_error("Backup Failed for $my_file", E_USER_WARNING);
                }
                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." . PHP_EOL; }
        if ($upload_success == 1) { echo "<br/><b>$my_file</b> has been saved." . PHP_EOL; }
        if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>" . PHP_EOL; }
        if ($upload_success < 0)  { echo "<br/><b>ERROR: $my_file NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</b>" . PHP_EOL; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded." . PHP_EOL;
            if (!chmod ($my_new_file, 0755))
            {
                echo '<br/>chmod(0755) FAILED: fileperms() = ';
                echo substr(sprintf('%o', fileperms($my_new_file)), -4);
            }
            echo '<br/><a target="_blank" href="' . $my_file . '">See the file ' . $my_file . '</a>' . PHP_EOL;
        }
    // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
    }
// END ACTION SCRIPT
}


// FORM SCRIPT: CREATE THE INPUT STATEMENTS FOR THE FILES
$inputs = NULL;
for ($n = 0; $n < $nf; $n++)
{
    $inputs .= '<input name="userfile' . $n . '" type="file" size="80" /><br/>' . PHP_EOL;
}

// CREATE THE HTML FORM USING HEREDOC NOTATION
$form = <<<EOF
<h2>Upload from 1 to $nf file(s)</h2>
<!--
    SOME IMPORTANT THINGS TO NOTE ABOUT THIS FORM...
    ENCTYPE= ATTRIBUTE IN THE HTML <FORM> TAG
    MAX_FILE_SIZE HIDDEN CONTROL MUST PRECEDE THE FILE INPUT CONTROLS
    INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN _FILES ARRAY
    ABSENCE OF ACTION= ATTRIBUTE IN <FORM> TAG CAUSES POST TO SAME URL
-->
<form name="UploadForm" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
<p>
Find the file(s) you want to upload and click the "Upload" button below.
</p>

$inputs

<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
<input type="submit" value="Upload" />
</form>
EOF;

echo $form;

Open in new window

Avatar of sammySeltzer

ASKER

Thanks guys for your kind responses. I have been trying to work out some issues based on feedbacks but having all sorts of problems.

First error: Warning: array_filter() expects parameter 1 to be array, null given in... which is this line:

  $_FILES['item']['tmp_name'] =   array_filter($_FILES['item']['tmp_name']);

Open in new window


When I commented that out, I got this new error:
Warning: Invalid argument supplied for foreach() in ...

which is this line:
 
 foreach($_FILES['item']['name'] as $i => $value ) {

Open in new window


I have never done this in php. I have done it in asp.net but mostly in classic asp.

So, kind of winging my way with this.

    $target = $_SERVER['DOCUMENT_ROOT']."/uploads";
    // I am filtering the files incase there are empty uploads
    // You need to have the proper file input name (item)
    $_FILES['item']['name'] =   array_filter($_FILES['item']['name']);
    $_FILES['item']['type'] =   array_filter($_FILES['item']['type']);
    $_FILES['item']['size'] =   array_filter($_FILES['item']['size']);
  //  $_FILES['item']['tmp_name'] =   array_filter($_FILES['item']['tmp_name']);

    foreach($_FILES['item']['name'] as $i => $value ) {
            $file_name              =   $_FILES['item']['name'][$i];
            $file_size              =   $_FILES['item']['size'][$i];
            $file_tmp               =   $_FILES['item']['tmp_name'][$i];
            $file_type              =   $_FILES['item']['type'][$i];

            $name                   =   ms_escape_string($_POST['nameMember']);
            $bandMember             =   ms_escape_string($_POST['bandMember']);
            $about                  =   ms_escape_string($_POST['aboutMember']);
            $bands                  =   ms_escape_string($_POST['otherBands']);
            $sqlArr['values'][$i]   =   "'".ms_escape_string($_FILES['item']['name'][$i])."'";
            $sqlArr['columns'][$i]  =   "Addend".$i;
            $sqlArr['columns']  =   "SignInSheet";
            $sqlArr['columns']  =   "TabSheet";
            // At this point you are only notifying user.
            // You have no code to prevent this limitation.
            if ($file_type!="application/pdf" || $file_type!="image/gif" || $file_type!="image/jpeg")
                 $errors[] =    'You can only upload PDFs, JPEGs or GIF files.<br>';
            // So far, this is just for notification, you haven't
            // actually done anything about this limitation
            if($file_size > 2097152)
                $errors[]='File size must be less than 2 MB';

            // Makes the folder if not already made.
            if(!is_dir($target))
                mkdir($target,0755,true);

            //Writes the files to the server
            if(move_uploaded_file($_FILES['item']['tmp_name'][$i], $target."/".$file_name)) {
                //If all is ok
                echo "The file ". $file_name. " has been uploaded to the directory and records saved to the database";
            }
            else {

            //Gives and error if its not
            echo "Sorry, there was a problem uploading your file.";
            }
        }

if(isset($sqlArr['columns'])) {
    // Because this is dependent on all images being uploaded properly, you
    // need more validation in your code. This code inserts no matter what.
    $sql="INSERT INTO tableName (nameMember,bandMember,'".implode("','",$sqlArr['columns'])."',aboutMember,otherBands)
VALUES ('$name', '$bandMember',".implode(",",$sqlArr['values']).", '$about', '$bands')" ;
    $objQuery = sqlsrv_query($conn, $sql);
    sqlsrv_close($conn);
} ?>

Open in new window


//markup snip:

      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>
      <td class="td_input_form"><input type="file" name="item[]" size="50"></td>

Open in new window


A user could choose to upload one or more but doesn't have to upload all the files at once.
You might want to copy the script I posted above and install it on your own server, then try running it.  When you see the form to upload files, use "View Source" to see how the HTML form is structured.  It should look something like this:
<h2>Upload from 1 to 3 file(s)</h2>
<!--
    SOME IMPORTANT THINGS TO NOTE ABOUT THIS FORM...
    ENCTYPE= ATTRIBUTE IN THE HTML <FORM> TAG
    MAX_FILE_SIZE HIDDEN CONTROL MUST PRECEDE THE FILE INPUT CONTROLS
    INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN _FILES ARRAY
    ABSENCE OF ACTION= ATTRIBUTE IN <FORM> TAG CAUSES POST TO SAME URL
-->
<form name="UploadForm" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="8388608" />
<p>
Find the file(s) you want to upload and click the "Upload" button below.
</p>

<input name="userfile0" type="file" size="80" /><br/>
<input name="userfile1" type="file" size="80" /><br/>
<input name="userfile2" type="file" size="80" /><br/>


<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
<input type="submit" value="Upload" />
</form>

Open in new window

Hi Ray,

Thanks for your response.

The reason I shied away from your code so far is I was having problem not just integrating with the INSERT statement but also the important fact that in addition to those items on the markup I posted, I have three additional files.

In all, a user could potentially upload 8 different files for eight different fieldnames.

From the example, I have Addend ( a total of 6 different fieldnames), Addend1...Addend6.

Then signInsheet, tabSheet and one more. Ok so 9.

I have set mine up in a way that you could tell when a field upload is for Addend1 or when it is for signInSheet, etc.

I will study yours a bit more and see if it helps me to continue to try and fix the issues with what I have or yours.
ASKER CERTIFIED SOLUTION
Avatar of sammySeltzer
sammySeltzer
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Please delete this question.

After much struggle, I was able to get my code to work exactly the way I want it to work.