Select destination folder for uploaded files

Hi,

New to php.  I found the following code here to upload multiple files to my site.  It works great.  I now need to modify it so that, on the same form, the user can select the server-side destination folder from a list of subfolders under the folder documents on the root of the site.  Can anyone help me with this?

Thanks
<!--- Begin Code --->

<?php // upload_documents_3.php
error_reporting(E_ALL);


// MANUAL REFERENCE PAGES
// http://docs.php.net/manual/en/features.file-upload.php
// http://docs.php.net/manual/en/features.file-upload.common-pitfalls.php
// http://docs.php.net/manual/en/function.move-uploaded-file.php
// http://docs.php.net/manual/en/function.getimagesize.php


// ESTABLISH THE NAME OF THE 'uploads' DIRECTORY
$uploads = 'assets\documents';

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT
$max_file_size = '8192000';  // EIGHT MEGABYTE LIMIT ON UPLOADS

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

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



// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED IN $_FILES[]["error"]
$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",
    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...
        NOTE THE CHOICE OF 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
    -->

    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" 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>

    <?php 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 <b>overwrite</b> existing files.
    <input type="submit" name="_submit" value="Upload" />
    </form>
    <?php
    die();
}
// END OF THE FORM SCRIPT




else // WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
{

// 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"]);

// MOVE THE FILE INTO THE DIRECTORY
// IF THE FILE IS NEW
        if (!file_exists($my_new_file))
        {
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_new_file))
            {
                $upload_success = 1;
            }
            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/><b>Attempted Backup Failed!</b>\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/><b><i>$my_file</i></b> has been saved.\n"; }
        if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>\n"; }
        if ($upload_success < 0)  { echo "<br/><b>ERROR <i>$my_file</i> NOT SAVED - SEE WARNING FROM move_uploaded_file() COMMAND</b>\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 ITERATOR
    }
}
?>

<!--- End Code --->

Open in new window

WaterstoneAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

HackneyCabCommented:
PHP always puts uploaded files into the same directory, and it's up to your form processing script to move the file if desired. See the PHP page about this:

http://www.php.net/manual/en/features.file-upload.post-method.php

However, I strongly suggest you do not let site visitors choose where to move files on your server. This is wide open to dangerous abuse unless you know what you're doing and you're very careful about it. If you're not careful, you end up with users uploading configuration files to your server's configuration directories, and then you're in trouble.
WaterstoneAuthor Commented:
Thanks for the reply and for the security concerns.   The code I attached to the question manages the upload to the temp folder and the copy to a hard-coded destination folder.  I need to now allow the user to pick from a drop-down list of all folder sunder the documents folder.

I can do this by listing the folders in a php form and creating a link to the upload php page that passes the destination folder as a parameter but the drop down list on the form would work better for us.

This process will be resticted to one admin user with avalid user id and password.
Ray PaseurCommented:
I don't have time to do all the integration programming -- that has to be your part of this, but I can show you a fairly safe design pattern for a drop-down select box of folders.  Install this script and run it to see the moving parts.  Best of luck with your project, ~Ray
<?php // RAY_dropdown_select_safety.php
error_reporting(E_ALL);
echo "<pre>" . PHP_EOL;


// SHOW HOW TO PRESENT AND PROCESS A DROPDOWN SELECT LIST
// MAN PAGE http://www.w3.org/TR/html401/interact/forms.html#h-17.6
// SHOW HOW TO LIMIT THE SELECTED VALUES TO PROTECT AGAINST HACKING


// THE ALLOWABLE VALUES IN AN ASSOCIATIVE ARRAY WITH KEYS POINTING TO THE EXTERNAL DISPLAY DATA
$safe_values = array
( 'abc' => 'ABC DISPLAY STRING'
, 'def' => 'DEF DISPLAY DATA'
, 'xyz' => 'XYZ DISPLAY '
)
;

// IF ANYTHING HAS BEEN POSTED IN THE SINGLE SELECT FORM
if (!empty($_POST["pick1"]))
{
    // TEST TO SEE IF THE POSTED DATA IS AMONG OUR ALLOWABLE KEYS
    $safe = FALSE;
    foreach ($safe_values as $key => $display_value)
    {
        if ($key == $_POST["pick1"])
        {
            $safe = TRUE;
            break;
        }
    }

    // SHOW WHAT WE GOT
    echo PHP_EOL . "HERE IS THE POST ARRAY: ";
    var_dump($_POST);

    // WAS THE CHOICE ACCEPTABLE?
    if ( $safe) echo PHP_EOL . "THIS IS A SAFE CHOICE BECAUSE $key == {$_POST["pick1"]}";
    if (!$safe) echo PHP_EOL . "UNDER ATTACK! RUN LIKE HELL!";
}

// START THE FORM
echo PHP_EOL . '<form method="post">';
echo PHP_EOL . 'PLEASE CHOOSE ONE FROM THIS LIST';
echo PHP_EOL . '<select name="pick1">';
echo PHP_EOL . '<option value="" selected="selected">CHOOSE ONE</option>';

// CREATE THE OPTIONS
foreach ($safe_values as $key => $display_value)
{
    echo
    '<option value="'
    . $key
    . '">'
    . $display_value
    . '</option>'
    .PHP_EOL;
}

// COMPLETE THE FORM
echo PHP_EOL . '</select>';
echo PHP_EOL . '<input type="submit" />';
echo PHP_EOL . '</form>';

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

WaterstoneAuthor Commented:
Thanks Ray.  You are invaluable resource for those of us relatively new to PHP.
Ray PaseurCommented:
Thanks for your kind words! I do my best ;-)
WaterstoneAuthor Commented:
Thanks!
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.