I have written a simple script to add files to an archive. After much head scratching I can't get the script to work.
I have a php file here which reads from a check-box, the file/s selected in the check-box are added to the array $file.
$path = ('a path');
$dir = scandir('another path');
if(isset($_POST["submit"])){
if(!isset($_POST["File"])){
echo 'A file must be selected to archive it';
} else {
require_once('zip_function.php');
$file = $_POST['File'];
$goZipper = goZipper($file, $path);
if($goZipper == false) {
echo ("Error");
} else {
echo ("Success");
}
}
}
The function goZipper is called and $file and the destination are passed to it, the function is below.
function goZipper($files, $destination = '',$overwrite = true) {
if(file_exists($destination) && !$overwrite) {
echo"File exists";
return false;
}
if(count($files)){
$zip = new ZipArchive();
if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true){
echo"Error opening destination";
return false;
}
foreach($files as $file){
$zip->addFile($file,basename($file));
echo("<pre>");
var_dump($zip);
exit();
}
$zip->close();
return file_exists($destination);
}
else{
return false;
}
}
The function is returning true every time it is called. But no files are being added. Can anyone spot an obvious error here?
ZipArchive::addFile() expects the first param to be a string containing the filename. But you are passing a value of $_POST['File'] to it which is an array as $_POST['File'] is a two dimensional array.
See here for the contents of $_POST['File'].
What you need to do is change this line:
$zip->addFile($file,basename($file));
To:
$zip->addFile($file['tmp_name'],$file['name']);