Meules
Meules

Reputation: 1389

How to get an id in front of file for upload

First of all I'm very new to PHP and a bit better with Jquery. I managed to build an upload iFrame to upload images to a dropbox account for a webshop.

So somebody puts a T-shirt in the cart and then needs to upload some artwork. Customer clicks "upload" and is send to an iFrame which have the dropbox upload script. The url of the iFrame is something like this -> http://webshop.com/dropbox/index.html?id=10102013-88981

So far so good. The problem is however that when two people upload a file with the same name, the first file is being updated. So I need to have an unique id in front of the file. That unique id is the parameter at the end of the url.

So the question is how to get the id at the end of the url and how to place it in front of the uploaded image?

Ideal would be either a prefix for the file name or store everything in it's own folder. I tried several things but my knowledge is limited, so any help greatly appreciated.

The upload script:

//Start the upload code.

........ 
......
    if(sizeof($_FILES)===0){
       echo "<li>No files were uploaded.</li>";
       return;
    }

    foreach ($_FILES['ufiles']['name'] as $key => $value) {

            if ($_FILES['ufiles']['error'][$key] !== UPLOAD_ERR_OK) {
                echo $_FILES['ufiles']['name'][$key].' DID NOT upload.';
                return;
            }

            $tmpDir = uniqid('/tmp/DropboxUploader-');
            if (!mkdir($tmpDir)) {
                echo 'Cannot create temporary directory!';
                return;
            }

            $tmpFile = $tmpDir.'/'.str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);
            if (!move_uploaded_file($_FILES['ufiles']['tmp_name'][$key], $tmpFile)) {
                echo $_FILES['ufiles']['name'][$key].' - Cannot rename uploaded file!';
                return;
            }

    try {
            $uploader = new DropboxUploader($drop_account, $drop_pwd );
            $uploader->upload($tmpFile, $drop_dir);

            echo "<li>".$_FILES['ufiles']['name'][$key]."</li>" ;

           // Clean up
           if (isset($tmpFile) && file_exists($tmpFile))
               unlink($tmpFile);

           if (isset($tmpDir) && file_exists($tmpDir))
               rmdir($tmpDir);

        } catch(Exception $e) {
            $error_msg = htmlspecialchars($e->getMessage());
            if($error_msg === 'Login unsuccessful.' ) {
             echo '<li style="font-weight:bold;color:#ff0000;">Unable to log into Dropbox</li>';
             return;
            }
             if($error_msg === 'DropboxUploader requires the cURL extension.' ) {
             echo '<li style="font-weight:bold;color:#ff0000;">Application error - contact admin.</li>';
             return;
            }

            echo '<li>'.htmlspecialchars($e->getMessage()).'</li>';
        }

    }

UPDATE AS REQUESTED

The form:

    <form class="formclass" id="ufileform" method="post" enctype="multipart/form-data">
         <fieldset>

       <div><span class="fileinput"><input type="file" name="ufiles" id="ufiles" size="32" multiple /></span>
</div>
        </fieldset>             
       <button type="button" id="ubutton">Upload</button>
       <button type="button" id="clear5" onclick="ClearUpload();">Delete</button>

        <input type="hidden" name="id" id="prefix" value="" />
            </form>

Upload.js (file is downloadable as free script on the internet):

(function () {

   if (window.FormData) {
      var thefiles = document.getElementById('ufiles'), upload = document.getElementById('ubutton');//, password = document.getElementById('pbutton');
      formdata = new FormData();
      thefiles.addEventListener("change", function (evt) {
         var files = evt.target.files; //  FileList object
         var i = 0, len = this.files.length, file;
         for ( ; i < len; i++ ) {
            file = this.files[i];
            if (isValidExt(file.name)) {  //if the extension is NOT on the NOT Allowed list, add it and show it.
               formdata.append('ufiles[]', file);
               output.push('<li>', file.name, ' <span class="exsmall">',
                  bytesToSize(file.size, 2),
                  '</span></li>');
               document.getElementById('listfiles').innerHTML = '<ul>' + output.join('') + '</ul>';
            }
         }
         document.getElementById('filemsg').innerHTML = '';
         document.getElementById('filemsgwrap').style.display = 'none';         
         document.getElementById('ubutton').style.display = 'inline-block';
         document.getElementById('clear5').style.display = 'inline-block';
      }, false);

      upload.addEventListener('click', function (evt) {                 //monitors the "upload" button and posts the files when it is clicked
         document.getElementById('progress').style.display = 'block';   //shows progress bar
         document.getElementById('ufileform').style.display = 'none';   //hide file input form
         document.getElementById('filemsg').innerHTML = '';             //resets the file message area

         $.ajax({
            url: 'upload.php',
            type: 'POST',
            data: formdata,
            processData: false,
            contentType: false,
            success: function (results) {
              document.getElementById('ufileform').style.display = 'block';
              document.getElementById('progress').style.display = 'none';
              document.getElementById('filemsgwrap').style.display = 'block';
              document.getElementById('filemsg').innerHTML = '<ul>' + results + '</ul>';
              document.getElementById('listfiles').innerHTML = '<ul><li>Select Files for Upload</ul>';
              document.getElementById('ufiles').value = '';
              document.getElementById('ubutton').style.display = 'none';
              document.getElementById('clear5').style.display = 'none';
              formdata = new FormData();
              output.length = 0;
            }
         });
      }, false);
   } else {
     // document.getElementById('passarea').style.display = 'none';
      document.getElementById('NoMultiUploads').style.display = 'block';
      document.getElementById('NoMultiUploads').innerHTML = '<div>Your browser does not support this application. Try the lastest version of one of these fine browsers</div><ul><li><a href="http://www.mozilla.org" title="Mozilla Firefox"><img src="images/firefox-logo.png" alt="Mozilla Firefox" /></a></li><li><a href="http://www.google.com/chrome" title="Google Chrome"><img src="images/google-chrome-logo.png" alt="Google Chrome Firefox" /></a></li><li><a href="http://www.apple.com/safari/download/" title="Apple Safari"><img src="images/apple-safari-logo.png" alt="Apple Safari" /></a></li><li><a href="http://www.maxthon.com/" title="Maxthon"><img src="images/maxthon-logo.png" alt="Maxthon" /></a></li></ul>';
   }

 document.getElementById('multiload').style.display = 'block';
 document.getElementById('ufileform').style.display = 'block';

}());

function ClearUpload() {  //clears the list of files in the 'Files to Upload' area  and resets everything to be ready for new upload
     formdata = new FormData();
     output.length = 0;
     document.getElementById('ufiles').value = '';
     document.getElementById('listfiles').innerHTML = 'Select Files for Upload';
     document.getElementById('ubutton').style.display = 'none';
     document.getElementById('clear5').style.display = 'none';
     document.getElementById('filemsgwrap').style.display = 'none';
}

function getExtension(filename) {  //Gets the extension of a file name.
     var parts = filename.split('.');
     return parts[parts.length - 1];
}

function isValidExt(filename) {  //Compare the extension to the list of extensions that are NOT allowed.
     var ext = getExtension(filename);
     for(var i=0; i<the_ext.length; i++) {
          if(the_ext[i] == ext) {
               return false;
               break;
          }
     }
return true;
}

Upvotes: 0

Views: 134

Answers (2)

cmorrissey
cmorrissey

Reputation: 8583

Change this line

$tmpFile = $tmpDir.'/'. $_POST['id'] . '-' . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);

Note the $_POST['id'] which was added

EDIT: Changed to $_POST

Also in your form which you are posting add

<input type="hidden" name="id" value="<?=$_GET['id']; ?>" />

Upvotes: 1

TheFrozenOne
TheFrozenOne

Reputation: 1715

You could simply at time() to your file name.

http://php.net/manual/de/function.time.php

$tmpDir. '/' . time() . str_replace("/\0", '_', $_FILES['ufiles']['name'][$key]);

Upvotes: 0

Related Questions