So, I watched a tutorial from a youtube video here how to zip a file using php. This is the code I copied.
This is the form to upload zip. I choose 7 files and then name the archive name "testing".
After I clicked the "Add Files to Zip", the files are zipped and are sent to the directory.
These are the code
HTML Code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Zip Archiving Tutorial</title>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
Archive Name: <input type="text" name="name"><br />
<input type="file" name="files[]" multiple="true">
<input type="submit" name="create" value="Create Zip"><br><br>
<input type="submit" name="upload" value="Upload to Database">
</form>
PHP Code:
<?php
if(isset($_POST['create']))
{
$filesArray = $_FILES["files"];
for($num = 0; $num < count($filesArray["name"]); $num++)
{
$fileName = $filesArray["name"][$num];
$tempName = $filesArray["tmp_name"][$num];
move_uploaded_file($tempName,"tmp/".$fileName);
}
$archiveName = $_POST['name'].".zip";
$filesArrayNames = $_FILES["files"]["name"];
$zipsDir = scandir("zips/");
$error = false;
foreach($zipsDir as $zipDirFile)
{
if($zipDirFile == $archiveName)
{
$error = true;
break;
}
}
if($error == false)
{
$tmpDir = scandir("tmp/");
$zip = new ZipArchive;
$zip->open("zips/".$archiveName, ZipArchive::CREATE);
for($num = 0; $num < count($filesArray["name"]); $num++)
{
$fileName = $filesArray["name"][$num];
foreach($tmpDir as $tmpDirFile)
{
if($tmpDirFile == $fileName)
{
$zip->addFile("tmp/".$fileName);
echo "Adding: ".$fileName."<br />";
}
}
}
$zip->close();
for($num = 0; $num < count($filesArray["name"]); $num++)
{
$fileName = $filesArray["name"][$num];
foreach($tmpDir as $tmpDirFile)
{
if($tmpDirFile == $fileName)
{
unlink("tmp/".$fileName);
}
}
}
}
else
{
echo "Name already exists";
}
}
if (isset($_POST['upload']))
{
//code to add for uploading zip file to database
}
?>
But is it possible to upload the zip file after it is the files is zipped through php? I want the user to upload the files after the files are zipped.
PHP
does not work on the user machine(the client) but in the server, so if you want to zip and then upload files think of scripts that run in the client side like javascript
(angularjs
, jquery
and other libraries you can use) to use to zip you file and php to accept them into the server.