简体   繁体   中英

I am not able to create and store a zip file using php

I am trying to create a code which selects a csv file from the local computer via file upload control. The csv file contains the names of the files I want to download from the server. When I press the submit button the code reads the csv file and extracts the names of the files which has to be downloaded. Now the code should create a zip file and add only those files to zip file which are mentioned in the csv file. For that I have created the following code:

<?php
if(isset($_POST['submit'])){
$filename=$_FILES['filename'];
$handle = fopen($_FILES['filename']['tmp_name'],"r");
$i=0;
  while(($data = fgetcsv($handle,1000,","))!== FALSE){
  $filenum[$i]=$data[0];
  $i++;
}
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false

    if(file_exists($destination) && !$overwrite) { return false; }
    //vars

    $valid_files = array();
    //if files were passed in...
    if(is_array($files)) {
        //cycle through each file

        foreach($files as $file) {
            //make sure the file exists

            if(file_exists("uploadedfiles/".$file)) {
                $valid_files[] = $file;
            }
        }
    }
    //if we have good files...
    if(count($valid_files)) {
        //create the archive
        $zip = new ZipArchive();

        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        //add the files
        foreach($valid_files as $file) {

            $zip->addFile($file,$file);
        }
        print_r($zip);
        //debug
        echo 'The zip archive contains ',$zip->numFiles,' files with a status of ',$zip->status;
        if (file_exists($destination) ){
        // push to download the zip
        echo "hiii";
        header('Content-type: application/zip');
        header('Content-Disposition: attachment; filename="' . $destination . '"');
        readfile($destination);
        // remove zip file is exists in temp path
        unlink($destination);
    } else {
        echo "error";
    }

        //close the zip -- done!
        $zip->close();
        //check to make sure the file exists
        return file_exists($destination);
    }
    else
    {
        return false;
    }
}
$result = create_zip($filenum,$_SERVER['DOCUMENT_ROOT'].'/misc/my-archive.zip');
}
?>
<form enctype='multipart/form-data' action='fileuploadproject.php' method='post'>
<input size='50' type='file' name='filename' id='filename'><br>
<input type='submit' name='submit' value='Download'>
</form>

I am getting the names of the csv files names added to the zip file when the statement print_r($zip); is executed but I cannot find the file created in the server folder. And so I cannot download the files. What should be done inorder to get the filenames in the csv file get added to the zip file and then download it to local pc. Please help me find where am I mistaken. Thanks.

This line

echo "hiii";

will block the header() to be send, since you can't send headers if there is content on the new-loaded page. Moreover, if you're adding content after, then your zip will be corrupted. Try without printing anything before and after, and it would works.

Oh, and as pointed by pokeybit, you're unlinking a file then verify it's existing. This is no sense. Moreover, if you're not passing in

    if(count($valid_files)) {

, the $zip->close(); won't work, because $zip isn't declared.

Thanks to dlegall pokeybit and all others who tried to help me solve the problem. I have done many changes in the code and finally the code which worked for me is given below:

<?php
if(isset($_POST['submit'])){
$filename=$_FILES['filename'];
$handle = fopen($_FILES['filename']['tmp_name'],"r");
$i=0;
  while(($data = fgetcsv($handle,1000,","))!== FALSE){
  $filenum[$i]=$data[0];
  $i++;
  }

    $valid_files = array();
    //if files were passed in...
    if(is_array($filenum)) {
        //cycle through each file
        foreach($filenum as $file) {
            //make sure the file exists
            if(file_exists("uploadedfiles/".$file)) {
                $valid_files[] = $file;
            }
        }
 }

    //if we have good files...
if(count($valid_files)) {
        //create the archive
        $zip = new ZipArchive;
if ($zip->open("uploadedfiles/archive.zip",  ZipArchive::CREATE)) {
            foreach($valid_files as $file) {
            $zip->addFile("uploadedfiles/".$file,$file);
        }
        $zip->close();
}
else
{
        echo "Not Created";
}

        if (file_exists("uploadedfiles/archive.zip") ){
        // push to download the zip
        $archive_file_name="uploadedfiles/archive.zip";
        $archive_file="archive.zip";
        header("Content-type: application/zip"); 
        header("Content-Disposition: attachment; filename=$archive_file"); 
        header("Pragma: no-cache"); 
        header("Expires: 0"); 
        readfile("$archive_file_name");
        unlink($archive_file_name);
        exit;
    } else {
        echo "There was some problem in downloading the file";
    }
}
else{
 echo "<script>alert('No files in the CSV match the files on the server');</script>";
}

} 
?>

<form enctype='multipart/form-data' action='fileuploadproject.php' method='post'>
Select the CSV file: <input style="color:white;background:coral;font-size:16px" size='50' type='file' name='filename' id='filename' required>
<input style="color:white;background:green;font-size:20px" type='submit' name='submit' value='Download'>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM