Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 parameter.

So, accessing loadZIP.php?param=blue, will open up the zip file, and replace some text in a text file I specify with 'blue', and allow the user to download this edited zip file.

I've looked over all of the PHP ZIP functions, but I can't find a simple solution. It seems like a relatively easy problem, and I believe I'm over thinking it. Before I go and write some overly complex functions, I was wondering how you'd go about this.

like image 299
Bryant Avatar asked Nov 03 '10 08:11

Bryant


People also ask

How do I edit text in a zip file?

Open the zip file with winrar, double click an embedded text file, it should open in an external editor. Change and close the text file. Winrar then asks if it should updated the archive with the changed file. Save this answer.

Can you edit files in a ZIP?

In some use cases documents may be placed inside zip files, which can be part of multifile document. If user wants to edit some of documents inside zip in M-Files, it is not necessary to copy zip file to computer. Editing inside zip can be done also directly in M-Files.

How to add files to zip in PHP?

Make a PHP file to save and create zip file$_FILES["file"]["name"]); $zip = new ZipArchive(); // Load zip library $zip_name ="upload. zip"; // Zip name if($zip->open($zip_name, ZIPARCHIVE::CREATE)!


2 Answers

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).

like image 125
clarkf Avatar answered Sep 20 '22 14:09

clarkf


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';
}
?>
like image 30
Ro Achterberg Avatar answered Sep 20 '22 14:09

Ro Achterberg