重命名文件,然后将其压缩

时间:2017-07-03 18:52:12

标签: php zip

我正在使用以下代码压缩一些文件,但我需要在压缩它们之前将它们重命名。

这是我的代码:

function create_zip($files = array(),$destination = '',$overwrite = false) {
    if(file_exists($destination) && !$overwrite) { return false; }
    $valid_files = array();
    if(is_array($files)) {
        foreach($files as $file) {
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    if(count($valid_files)) {
        $zip = new ZipArchive();
        if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) {
            return false;
        }
        foreach($valid_files as $file) {
            $zip->addFile($file, basename($file));
        }

        $zip->close();

        return file_exists($destination);
    }
    else {
        return false;
    }
}

$query = "SELECT tracks.*, orders_temp.* FROM tracks LEFT JOIN orders_temp ON tracks.trackID = orders_temp.track WHERE session_id = '".session_id()."'";
$result = $conn->query($query);
$files_to_zip = array();

while($row = $result->fetch_object()){
    $files_to_zip[] = 'uploads/music/' . $row->trackMP3;


    $query_got = "SELECT * FROM downloads WHERE downloadTrack = $row->trackID AND downloadUser = $uid";
    $result_got = $conn->query($query_got);

    if ($result_got->num_rows == 0) {
        $query1 = "INSERT INTO downloads(downloadTrack, downloadUser) values($row->trackID,$uid)";
        $result1 = $conn->query($query1);
    }
}

$zipped = 'uploads/zipped/mashup-' . session_id() . '.zip';


$result = create_zip($files_to_zip,$zipped);
$file = 'mashup-' . session_id() . '.zip';
$fp = fopen($zipped, 'rb');

header("Content-Transfer-Encoding: binary"); 
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$file");
header("Content-Length: " . filesize($zipped));
fpassthru($fp);

我基本上希望$row->trackName在进入zip文件而不是$row->trackMP3时成为文件的名称。

0 个答案:

没有答案