zip_entry_name()
The zip_entry_name() function is a built-in function in PHP that is used to get the name of a file in a zip archive. The name of the file is the path of the
The zip_entry_name() function is a legacy PHP function used to get the name of a file in a zip archive. The returned name is the path of the file relative to the root of the zip archive.
Compatibility Note: The legacy procedural
zip_*functions were deprecated in PHP 7.4 and removed in PHP 8.0. This tutorial covers the legacy syntax for historical reference. For modern PHP applications, use theZipArchiveclass, which is the only viable option in PHP 8.0+.
Syntax
The syntax of the zip_entry_name() function is as follows:
Syntax of the zip_entry_name() function in PHP
string zip_entry_name(resource $zip_entry)Where $zip_entry is a resource handle returned by zip_read() for an entry in the zip archive.
Usage Examples
Let's look at a practical example of retrieving a file name from a zip archive.
Example: Legacy Usage (PHP 7.4 and Earlier)
The following example demonstrates how to open a zip archive, iterate through its entries, and retrieve each entry's name using the legacy zip_* functions:
Retrieving File Names from a Zip Archive in Legacy PHP
$zip = zip_open('example.zip');
if ($zip) {
while ($zip_entry = zip_read($zip)) {
echo zip_entry_name($zip_entry) . "\n";
zip_entry_close($zip_entry);
}
zip_close($zip);
}This code opens example.zip, reads each entry sequentially, prints its name using zip_entry_name(), and properly closes both the entry and the archive.
Example: Getting the Name of a File in a Zip Archive (Modern PHP)
Since the legacy zip_* functions are removed in PHP 8.0+, the recommended approach is to use the ZipArchive class. This example demonstrates how to open an archive, read the first entry, and get its name with proper error handling and resource cleanup:
Getting the Name of a File in a Zip Archive in PHP
$zip = new ZipArchive();
$zipFile = 'example.zip';
if ($zip->open($zipFile) === true) {
// Get the name of the first entry
$fileName = $zip->getNameIndex(0);
echo "The name of the file is: " . $fileName;
$zip->close();
} else {
echo "Failed to open the archive.";
}This code creates a ZipArchive instance and opens example.zip. It retrieves the name of the first entry using getNameIndex(0), outputs it, and properly closes the archive. If the archive cannot be opened, an error message is displayed.
Conclusion
In this article, we've discussed the zip_entry_name() function and its role in retrieving file names from zip archives. We've explained its syntax and provided both legacy and modern examples. By using ZipArchive in your applications, you can reliably manage zip archives and access file metadata.
Practice
What does the zip_entry_name() function in PHP do?