Question

I'm trying to use dropzone.js to add an easy drag-and-drop interface for a user to upload up to 10 photos to my server (currently WAMP). I'm using PHP 5.4 on the back end.

Following this tutorial I got the system working enough to upload acceptable file types to an 'Uploads' folder in my root directory, but I'm stuck on how to make the photos instead upload to a unique directory for each user.

By the time the user gets to my photo upload page, they've already created a folder on my server with a unique name, the path to which has been stored in $_SESSION['requestedDirectory'].

Here is the code used to display the Dropzone form:

<form action="<?php echo BASE_URL; ?>photo_uploads.php" class="dropzone" id="photoUploadDropzone"></form>

<script type="text/javascript">
    Dropzone.options.photoUploadDropzone = {
      paramName: "file",
      maxFilesize: 5, // MB
      maxFiles: 10,
      addRemoveLinks: true,
      acceptedFiles: "image/jpeg, image/jpg, image/png, image/gif",
      accept: function(file, done) {
        done();
      }
    };
</script>

As you can see, it sends the data to a file called photo_uploads.php, which has the following code:

if (!empty($_FILES)) {
  $tempFile = $_FILES['file']['tmp_name'];
  $targetPath = $_SESSION['requestedDirectory']; <--HERE'S THE PROBLEM LINE
  $targetFile =  $targetPath. $_FILES['file']['name'];
  move_uploaded_file($tempFile,$targetFile);
}

As mentioned in the comment above, this file doesn't seem to be able to take data out of a session variable, but I'm not sure why. If I change that line to give the full directory (eg $targetPath = 'C://wamp/www/shops/foldername';) it works fine, but then of course I can't change that foldername dynamically based on which user is using the form.

So to clarify, I'd like to know how to upload the file to the path stored in Session?

UPDATE: Solved.

For anyone else with the same problem in future, this is what I changed the form to:

<form action="<?php echo BASE_URL; ?>photo_uploads.php?folder=<?php echo $_SESSION['photosDir']; ?>" class="dropzone" id="photoUploadDropzone"></form>

Like Rizwan suggested, by passing the $_SESSION['photosDir'] value in a GET variable it was accessible after the form posted.

The other change I made was to photo_uploads.php, just to the following line:

$targetPath = $_GET['folder'];

Absolutely no idea why the value wasn't available directly from Session in the first place - I've never heard of Session values going out of scope - but happy to have this problem solved.

Was it helpful?

Solution

You can pass the requestedDirectory as a query string with the form's action attribute. In that way it can be accessible.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top