Uploading multiple files in a directory

Discussion in 'PHP' started by elusid, Oct 8, 2009.

  1. #1
    I've searched google over and over looking for a solution for uploading multiple files in a directory at once with php... I know its possible but how? only help I can find is for uploading a single file...
     
    elusid, Oct 8, 2009 IP
  2. dsignresponder

    dsignresponder Greenhorn

    Messages:
    81
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    18
    #2
    Here's a good multi-upload script I'm using :
    
    
    // make a note of the current working directory relative to root.
    $directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
    
    // make a note of the location of the upload handler
    $uploadHandler = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'your_uploadhandler.php';
    
    // set a max file size for the html upload form
    $max_file_size = 300000; // size in bytes
    
    // make a note of the directory that will recieve the uploaded files
    $uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploads/';
    
    // make a note of the location of the upload form in case we need it
    $uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload_form.php'; // can be the same file
    
    // make a note of the location of the success page
    $uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'success.php';  // can be the same file
    
    // name of the fieldname used for the file in the HTML form
    $fieldname = 'file';
    
    // Now let's deal with the uploaded files
    
    // possible PHP upload errors
    $errors = array(1 => 'php.ini max file size exceeded',
                    2 => 'html form max file size exceeded',
                    3 => 'file upload was only partial',
                    4 => 'no file was attached');
    
    // check the upload form was actually submitted else print form
    isset($_POST['add'])
        or error('the upload form is needed', $uploadForm);
        
    // check if any files were uploaded and if
    // so store the active $_FILES array keys
    $active_keys = array();
    foreach($_FILES[$fieldname]['name'] as $key => $filename)
    {
        if(!empty($filename))
        {
            $active_keys[] = $key;
        }
    }
    
    // check at least one file was uploaded
    count($active_keys)
        or error('No files were uploaded', $uploadForm);
            
    // check for standard uploading errors
    foreach($active_keys as $key)
    {
        ($_FILES[$fieldname]['error'][$key] == 0)
            or error($_FILES[$fieldname]['tmp_name'][$key].': '.$errors[$_FILES[$fieldname]['error'][$key]], $uploadForm);
    }
        
    // check that the file we are working on really was an HTTP upload
    foreach($active_keys as $key)
    {
        @is_uploaded_file($_FILES[$fieldname]['tmp_name'][$key])
            or error($_FILES[$fieldname]['tmp_name'][$key].' not an HTTP upload', $uploadForm);
    }
        
    // validation... since this is an image upload script we
    // should run a check to make sure the upload is an image
    foreach($active_keys as $key)
    {
        @getimagesize($_FILES[$fieldname]['tmp_name'][$key])
            or error($_FILES[$fieldname]['tmp_name'][$key].' not an image', $uploadForm);
    }
        
    // make a unique filename for the uploaded file and check it is
    // not taken... if it is keep trying until we find a vacant one
    	$uploadFilename[$key] = $uploadsDirectory.$_FILES[$fieldname]['name'][$key];
    
    $nameArr = explode("/",$uploadFilename[$key]);
    $newname = $nameArr[sizeof($nameArr_1)-2]."/".$nameArr_1[sizeof($nameArr_1)-1]; 
    
    // now let's move the file to its final and allocate it with the new filename
    foreach($active_keys as $key)
    {
        @move_uploaded_file($_FILES[$fieldname]['tmp_name'][$key], $uploadFilename[$key])
            or error('receiving directory insuffiecient permission', $uploadForm);
    }
        
    // If you got this far, everything has worked and the file has been successfully saved.
    // We are now going to redirect the client to the success page.
    header('Location: ' . $uploadSuccess);
    
    // make an error handler which will be used if the upload fails
    function error($error, $location, $seconds = 5)
    {
        header("Refresh: $seconds; URL=\"$location\"");
        echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
        '"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
        '<html lang="en">'."\n".
        '    <head>'."\n".
        '        <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
        '        <link rel="stylesheet" type="text/css" href="stylesheet.css">'."\n\n".
        '    <title>Upload error</title>'."\n\n".
        '    </head>'."\n\n".
        '    <body>'."\n\n".
        '    <div id="Upload">'."\n\n".
        '        <h1>Upload failure</h1>'."\n\n".
        '        <p>An error has occured: '."\n\n".
        '        <span class="red">' . $error . '...</span>'."\n\n".
        '         The upload form is reloading</p>'."\n\n".
        '     </div>'."\n\n".
        '</html>';
        exit;
    } // end error handler
    
    // redirect to current page so if we click the refresh button
    // the form won't be resubmitted ( as that would make duplicate entries )
    header('Location: ' . $_SERVER['REQUEST_URI']);
    
    exit;
    }
    ob_end_flush();
    
    // YOUR UPLOAD FORM SHOULD GO HERE something like :
    
        <form id="Upload" action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post">
    
        <p>
        <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>">
        </p>
    
    // ETC......
    
    
    PHP:
    It's doing great job for me!
     
    dsignresponder, Oct 9, 2009 IP
  3. elusid

    elusid Peon

    Messages:
    890
    Likes Received:
    21
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks! that is pretty sweet. Its not exactly what i'm looking for but it will come in handy.

    I basically need a function that will look at a directory recursively take note of all the files and directories within and then upload them to a specified location via ftp..
     
    elusid, Oct 9, 2009 IP
  4. dsignresponder

    dsignresponder Greenhorn

    Messages:
    81
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    18
    #4
    I see.
    No problem, that can be done too. Use this script to 'read' all the files within a directory :

    
    if (is_dir($target_dir)) {
    if ($dh = opendir($target_dir)) {
    while (($file = readdir($dh)) !== false) {
    
    if (filetype($target_dir . "/" . $file) == "file")
    echo $file " - " .
    round(filesize($target_dir . "/" . $file)/1024) . "K " . date
    ("m/d/Y H:i:s", filemtime($target_dir . "/" . $file)) ;
    }
    closedir($dh);
    }
    }
    
    PHP:
    Combine it with this script to upload your files :
    
    // FTP access parameters
    $host = 'ftp.example.org';
    $usr = 'example_user';
    $pwd = 'example_password';
     
    // file to move:
    $local_file = './example.txt';
    $ftp_path = '/data/example.txt';
     
    // connect to FTP server (port 21)
    $conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
     
    // send access parameters
    ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
     
    // turn on passive mode transfers (some servers need this)
    // ftp_pasv ($conn_id, true);
     
    // perform file upload
    $upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
     
    // check upload status:
    print (!$upload) ? 'Cannot upload' : 'Upload complete';
    print "\n";
    
    // close the FTP stream
    ftp_close($conn_id);
    
    PHP:
    Hope this might help...
     
    dsignresponder, Oct 11, 2009 IP
  5. Gray Fox

    Gray Fox Well-Known Member

    Messages:
    196
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    130
    #5
    One small notice you should probably consider, Mozilla uses "none" to indicate an empty upload field
    
    $_FILES['form_field']['name'] == "none";
    
    PHP:
     
    Gray Fox, Oct 12, 2009 IP