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.