PHP操作ZipArchive实现文件上传下载功能

当前位置: 电视猫 > php教程>
电视猫时间: 2024-07-08 15:07:16

  PHP操作ZipArchive实现文件上传下载功能

To implement file upload and download functionality using PHP and ZipArchive, follow these steps:

1. File Upload:

  • Create Upload Form: Create an HTML form with a file input field to allow users to select files for upload.
HTML
<!DOCTYPE html>
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <h1>File Upload</h1>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">Select files to upload:</label>
        <input type="file" id="file" name="files[]" multiple>
        <br>
        <input type="submit" value="Upload">
    </form>
</body>
</html>
  • Handle Upload in PHP: Create a PHP script (upload.php) to process the uploaded files.
PHP
<?php

if (isset($_FILES['files'])) {
    $files = $_FILES['files'];

    $zip = new ZipArchive(); // Create ZipArchive object
    $zipFileName = "uploaded_files.zip"; // Set zip file name

    if ($zip->open($zipFileName, ZIPARCHIVE::CREATE) !== true) {
        echo "Error creating zip file: " . $zip->getArchiveError();
        exit;
    }

    foreach ($files['error'] as $key => $error) {
        if ($error === UPLOAD_ERR_OK) {
            $fileName = $files['name'][$key];
            $tmpName = $files['tmp_name'][$key];

            if ($zip->addFile($tmpName, $fileName) === false) {
                echo "Error adding file to zip: " . $fileName;
            }
        }
    }

    $zip->close(); // Close zip file

    if (file_exists($zipFileName)) {
        // Download the zip file
        header('Content-Type: application/zip');
        header('Content-Disposition: attachment; filename=' . $zipFileName);
        header('Content-Length: ' . filesize($zipFileName));
        readfile($zipFileName);
        unlink($zipFileName); // Delete the temporary zip file after download
        exit;
    } else {
        echo "Error creating zip file";
    }
}

2. File Download:

  • Provide Download Link: Generate a download link on a separate page or within the upload page after successful upload.
HTML
<a href="download.php">Download Uploaded Files</a>
  • Create Download Script: Create a PHP script (download.php) to handle the file download.
PHP
<?php

$zipFileName = "uploaded_files.zip"; // Set zip file name

if (file_exists($zipFileName)) {
    // Download the zip file
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename=' . $zipFileName);
    header('Content-Length: ' . filesize($zipFileName));
    readfile($zipFileName);
    unlink($zipFileName); // Delete the temporary zip file after download
    exit;
} else {
    echo "Uploaded file not found";
}

This setup provides basic file upload and download functionality using PHP and ZipArchive. You can enhance it by adding error handling, progress tracking, and more robust file management.

    最新电视剧
    热门电视剧
    影视资讯
    最新剧情排行榜
    最新电视剧剧情