PHP Pclzip 库:在压缩之前重命名文件


PHP Pclzip library: To rename files before being compressed

我正在使用PHP PclZip库来生成动态zip存档,并且添加到zip存档中的文件具有随机名称。

//These are just examples and not part of the actual code
$image = 'random_image_name_ahnfhhsdf.png';
$audio = 'random_audio_name_ahnfhhsdf.mp3';
$pdf = 'random_pdf_name_ahnfhhsdf.mp3';

$archive = new PclZip($zip_folder_path);
$archive->add($image, PCLZIP_OPT_REMOVE_ALL_PATH);
$archive->add($audio, PCLZIP_OPT_REMOVE_ALL_PATH);
$archive->add($pdf, PCLZIP_OPT_REMOVE_ALL_PATH);

当这些文件添加到存档中时,它们将使用相同的名称添加(random_image_name_ahnfhhsdf.png ...等等)。我想做的是给他们一个一致的命名约定,例如。tutorial_image.png、tutorial_audio.mp3和tutorial_document.pdf。有没有办法做到这一点?或者,简而言之,有没有办法在将文件添加到存档之前重命名文件?

请知道,我知道使用 php 创建存档的替代方法(例如 Ziparchive),由于已经使用该库创建的代码,我正在使用该库。

我想

您可以在存档之前rename()文件。例如:

`$image = 'random_image_name_ahnfhhsdf.png';
rename($image, 'tpzip'newfile.png')`

压缩后,您可以删除这些新文件。


我在这里为单个文件找到了另一种解决方案。这适用于您的问题。但是,如果您有大量文件,这可能会减慢存档过程。试试这段代码。

$archive = new PclZip("archive.zip");
$new_filename = "new_file_name";
$v_content = file_get_contents( "path to your file" );
$list = $archive->create(
    array(
        array(
            PCLZIP_ATT_FILE_NAME => $new_filename,
            PCLZIP_ATT_FILE_CONTENT => $v_content
        )
    )
);
if ($list == 0) {
  die("ERROR : '".$archive->errorInfo(true)."'");
}else{
    echo "Success";
}