Current Location: Home> Latest Articles> Complete Guide to Modifying File Attributes in PHP ZipArchive

Complete Guide to Modifying File Attributes in PHP ZipArchive

M66 2025-06-10

Introduction to PHP ZipArchive

ZipArchive is a built-in PHP extension that allows developers to create, read, update, and modify ZIP compressed files. Among its many capabilities is the ability to access and change properties of files inside the archive, such as permissions and timestamps.

Initialize the Object and Load the ZIP Archive

Before making any changes, start by creating a ZipArchive object and opening the ZIP file you wish to work with:


$zip = new ZipArchive();
$zip->open('example.zip');

Read Original File Attributes

Use the statIndex() method to retrieve information about a file within the archive by its index. This method returns an associative array containing attributes such as the filename, uncompressed size, last modification time, and file permissions:


$fileIndex = 0; // Assuming the file is at the first index
$fileInfo = $zip->statIndex($fileIndex);

echo "Filename: " . $fileInfo['name'] . "\n";
echo "Uncompressed size: " . $fileInfo['size'] . " bytes\n";
echo "Last modified: " . date('Y-m-d H:i:s', $fileInfo['mtime']) . "\n";
echo "Permissions: " . $fileInfo['external'] . "\n";

Modify File Permissions and Timestamp

You can update file attributes using the setExternalAttributesIndex() method. This method accepts the file index and a new attribute value, typically including file permissions and modification time. Here's how to do it:


$newPermissions = 0777; // Set full permissions
$newModifiedTime = time(); // Set current timestamp

$zip->setExternalAttributesIndex($fileIndex, ($newPermissions << 16) | ($newModifiedTime & 0xFFFF));

// Verify the updated attributes
$fileInfo = $zip->statIndex($fileIndex);
echo "Updated permissions: " . $fileInfo['external'] . "\n";
echo "Updated modification time: " . date('Y-m-d H:i:s', $fileInfo['mtime']) . "\n";

Save Changes and Close the Archive

After applying changes, don’t forget to save them using the close() method, which finalizes the archive and releases the object:


$zip->close();

Conclusion

Using PHP's ZipArchive extension, you can easily access and modify internal file attributes in ZIP archives. By combining statIndex to fetch current metadata, setExternalAttributesIndex to update values, and close to finalize changes, managing file properties becomes a streamlined process.