Asked 3 years ago
30 Jun 2021
Views 411
Elwin

Elwin posted

PHP file upload and zip on upload

PHP file upload and zip on upload
Mitul Dabhi

Mitul Dabhi
answered Feb 27 '23 00:00


To allow users to upload files using PHP, you can use the $_FILES superglobal variable to access the uploaded file information. Here's an example of how to upload a file using PHP:

<form method="POST" action="" enctype="multipart/form-data">
    <input type="file" name="file[]" multiple>
    <input type="submit" name="submit" value="Upload and Zip">
</form>


To allow users to upload files and then zip them, you can use the following PHP code:

<?php
if(isset($_POST['submit'])){
    $file_array = $_FILES['file'];
    $file_count = count($file_array['name']);
    $zip = new ZipArchive();
    $zip_name = "uploads.zip";

    if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){
        echo "Could not create zip file";
    }

    for($i=0; $i<$file_count; $i++){
        $file_name = $file_array['name'][$i];
        $tmp_name = $file_array['tmp_name'][$i];
        $zip->addFile($tmp_name, $file_name);
    }

    $zip->close();
    header("Content-type: application/zip"); 
    header("Content-Disposition: attachment; filename=$zip_name");
    header("Pragma: no-cache"); 
    header("Expires: 0"); 
    readfile("$zip_name");
    unlink("$zip_name");
}
?>



The above code first checks if the form has been submitted using the isset() function. It then gets the file array using $_FILES['file'] and counts the number of files uploaded using the count() function. It then creates a new ZipArchive object and sets the zip file name to uploads.zip.

The open() method of the ZipArchive object is then used to create the zip file . If the zip file cannot be created, an error message is displayed.

A loop is then used to iterate through each file in the file array. The file name and temporary name are then retrieved using $file_array['name'][$i] and $file_array['tmp_name'][$i], respectively. The addFile() method of the ZipArchive object is then used to add the file to the zip file.

After all the files have been added to the zip file, the zip file is closed using the close() method of the ZipArchive object .

The headers are then set to allow the zip file to be downloaded using the header() function . The readfile() function is then used to output the zip file to the browser, and the unlink() function is used to delete the zip file from the server.

Finally, a form is displayed to allow users to upload files. The enctype attribute is set to multipart/form-data to allow files to be uploaded. The name attribute of the file input is set to file[] to allow multiple files to be uploaded at once. The type attribute of the submit button is set to submit and the name attribute is set to submit to allow the form to be submitted.
Post Answer