在外部服务器上压缩文件,然后在我的服务器上下载Zip


Zip file on external server and download the zip on my server

以下是我的要求,但我不明白如何使用PHP。

  1. 用户选择一些文件列表并点击下载
  2. 请求转到文件所在的外部服务器(使用HTTPS)
  3. 它压缩用户在步骤1中选择的那些文件集
  4. 然后压缩后的文件被下载到用户的系统上

我探索了不同的选项,比如使用SSH2、curl、file_get_contents。但我无法确定这一切将如何运作。

试试这个代码

create upload.php
<?php
    $error = "";        //error holder
    if(isset($_POST['compress'])){
        $post = $_POST;    
        $file_folder = "files/"; //Folder where files are exists   
        if(extension_loaded('zip'))
        {   // Checking ZIP extension is available
            if(isset($post['files']) && count($post['files']) > 0){ 
                $zip = new ZipArchive();            // create zip class object 
                $zip_name = time().".zip";          // Zip name
                if($zip->open($zip_name, ZIPARCHIVE::CREATE)!==TRUE){        // Open zip object
                    $error .=  "* Zip file could not be create<br/>";
                }
                foreach($post['files'] as $file){              
                    $zip->addFile($file_folder.$file);           // Adding files into zip
                }
                $zip->close();
                if(file_exists($zip_name)){
                    // push to download the zip
                    header('Content-type: application/zip');
                    header('Content-Disposition: attachment; filename="'.$zip_name.'"');
                    readfile($zip_name);
                    // remove zip file is exists in temp path
                    unlink($zip_name);
                }
            }else
                $error .= "* Please select file to zip <br/>";
        }else
            $error .= "* You dont have ZIP extension<br/>";
    }
?>

Create index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Download As Zip/RAR</title>
</head>
<body>
<center><h1>Create a Compress file with PHP</h1></center>
<form name="zips" method="post">
<table>
<?php
if($error!='')
{
    ?>
    <center><h5 style="color:red;"><?php echo $error; ?></h5></center>
    <?php
}
?>
    <tr>
        <td><input type="checkbox" name="files[]" value="car.jpg"></td><td><img src='car.jpg' width='50'></td><td>Car.jpg</td></tr>
        <tr><td><input type="checkbox" name="files[]" value="plane.jpg"></td><td><img src='plane.jpg' width='50'></td><td>Plane.jpg</td></tr>
        <tr><td><input type="checkbox" name="files[]" value="bike.jpg"></td><td><img src='bike.jpg' width='50'></td><td>Bike.jpg</td></tr>
        <tr><td><input type="submit" name="compress" value="compress"></td><td></td><td></td></tr>
</table>
</form>
</body>
</html>

您可以使用ziparchive创建zip文件,并且您可以让代码下载zip文件。

参考:

http://php.net/manual/en/class.ziparchive.php