Modifying a single text file in a ZIP file, in PHP

后端 未结 2 1720
忘了有多久
忘了有多久 2020-12-29 06:44

I have a ZIP file on my server. I want to create a PHP file, loadZIP.php that will accept a single parameter, and then modify a text file within the ZIP to reflect that par

相关标签:
2条回答
  • 2020-12-29 07:02

    In PHP 8 you can use ZipArchive::replaceFile

    As demonstrated by this example from the docs:

    <?php
    $zip = new ZipArchive;
    if ($zip->open('test.zip') === TRUE) {
        $zip->replaceFile('/path/to/index.txt', 1);
        $zip->close();
        echo 'ok';
    } else {
        echo 'failed';
    }
    ?>
    
    0 讨论(0)
  • 2020-12-29 07:21

    Have you taken a look at PHP5's ZipArchive functions?

    Basically, you can use ZipArchive::Open() to open the zip, then ZipArchive::getFromName() to read the file into memory. Then, modify it, use ZipArchive::deleteName() to remove the old file, use ZipArchive::AddFromString() to write the new contents back to the zip, and ZipArchive::close():

    $zip = new ZipArchive;
    $fileToModify = 'myfile.txt';
    if ($zip->open('test1.zip') === TRUE) {
        //Read contents into memory
        $oldContents = $zip->getFromName($fileToModify);
        //Modify contents:
        $newContents = str_replace('key', $_GET['param'], $oldContents)
        //Delete the old...
        $zip->deleteName($fileToModify)
        //Write the new...
        $zip->addFromString($fileToModify, $newContents);
        //And write back to the filesystem.
        $zip->close();
        echo 'ok';
    } else {
        echo 'failed';
    }
    

    Note ZipArchive was introduced in PHP 5.2.0 (but, ZipArchive is also available as a PECL package).

    0 讨论(0)
提交回复
热议问题