Rameez Shah
Rameez Shah

Reputation: 61

ZipArchive not creating file

if(isset($_POST['submit'])){
if(!empty($_FILES['files']['name'])){
  $Zip = new ZipArchive();
  $Zip->open('uploads.zip', ZIPARCHIVE::CREATE);
  $UploadFolder = "uploads/";
  foreach($_FILES['files'] as $file){
        $Zip->addFile($UploadFolder.$file);
  }
  $Zip->close();
}
 else {
     echo "no files selected";
}
}

What is wrong here ? I have just watched a tutorial of creating archives and adding files in it but it is not working ...I am using php 5.4 . It is not even giving me any error. Can any one please guide me what i am doing wrong here.

Below is the form

<form action="" method="POST" enctype="multipart/form-data">
            <label>Select files to upload</label>
            <input type="file" name="files">
            <input type="submit" name="submit" value="Add to archieve">
        </form>

Upvotes: 0

Views: 356

Answers (1)

Atli
Atli

Reputation: 7930

These lines don't make any sense

$UploadFolder = "uploads/";
foreach($_FILES['files'] as $file){
    $Zip->addFile($UploadFolder.$file);
}

At that point in the code you posted, no uploaded files have been moved to a uploads/ directory, and looping though the $_FILES["files"] element - which is an associative array of various values, only one of which is the actual file name - and adding each value to the ZIP as a file, is nonsensical. - You should read the PHP docs relating to file uploading. It's clear you don't really know how PHP handles file uploads yet, which you should learn before attempting things like this.

One solution would be to move the uploaded file to the uploads/ directory using move_uploaded_file, but seeing as you are only really using the file there to add it to the archive, that step is pretty redundant; you can just add it directly from the temp location. First you need to verify it, though, which you can do with the is_uploaded_file function.

// Make sure the file is valid. (Security!)
if (is_uploaded_file($_FILES["files"]["tmp_name"])) {
    // Add the file to the archive directly from it's
    // temporary location. Pass the real name of the file
    // as the second param, or the temporary name will be
    // the one used inside the archive.
    $Zip->addFile($_FILES["files"]["tmp_name"], $_FILES["files"]["name"]);

    $Zip->close();

    // Remove the temporary file. Always a good move when
    // uploaded files are not moved to a new location.
    // Make sure this happens AFTER the archive is closed.
    unlink($_FILES["files"]["tmp_name"]);
}

Upvotes: 1

Related Questions