上传php时压缩文件

时间:2018-08-21 10:24:16

标签: php zip compression

好的,所以我要上传文件,上传后它们具有加密的名称,问题是我想压缩它们,所以当到达链接时,它下载而不是显示

<?php
$fileName = $_FILES["file1"]["name"]; // The file name
$fileTmpLoc = $_FILES["file1"]["tmp_name"]; // File in the PHP tmp folder
$fileType = $_FILES["file1"]["type"]; // The type of file it is
$fileSize = $_FILES["file1"]["size"]; // File size in bytes
$fileErrorMsg = $_FILES["file1"]["error"]; // 0 for false... and 1 for true
if (!$fileTmpLoc) { // if file not chosen
    echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
}
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "#";



function generateRandomString($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$extension = pathinfo($fileName, PATHINFO_EXTENSION);
$string69 = generateRandomString();
$date = date("l") . "_" . date("d/m/Y");
$encyptstring = $string69 . "." . $extension;

if(move_uploaded_file($fileTmpLoc, "upload/VEMWdk/$string69.$extension")){
} else {
    echo "upload failed :( please contact iHaveDeBestName";
}
?>

在功能move_upload_file中,而不是原始的'$ extension',我希望将其压缩为.zip文件,因此,如果我上载文本文件,它将保存为以下内容: {randomString} .zip,该zip文件中将是文本文件。

我尝试了其他方法,但它所做的只是替换zip中的文件,我想为每个上传的文件创建新的zip

请忽略sqldB连接,该连接将用于记录上传

1 个答案:

答案 0 :(得分:1)

$zip = new ZipArchive();
$filename = "./test112.zip"; //Your Zip File with path

if ($zip->open($filename, ZipArchive::CREATE)!==TRUE) {
    exit("cannot open <$filename>\n");
}
$zip->addFile("{your_uploaded_file_with_path}"); // uploaded file
$zip->close();