Extracting ZIP Files with PHP
When attempting to unzip a file using PHP, you may encounter difficulties when passing the file name through a URL as seen in your code:
<?php $master = $_GET["master"]; system('unzip $master.zip'); // Incorrect syntax ?>
Correcting the Syntax
The primary issue lies in the syntax of the system() call. The correct syntax is to call the system command like so:
system("unzip $master.zip");
Using Built-in PHP Functions
While the system() function can accomplish the task, it's generally not recommended. PHP provides built-in extensions for handling compressed files, such as ZipArchive. Here's an example using ZipArchive:
<?php $zip = new ZipArchive; $res = $zip->open('file.zip'); if ($res === TRUE) { $zip->extractTo('/myzips/extract_path/'); $zip->close(); echo 'Extraction successful!'; } else { echo 'Extraction failed: ' . $zip->getStatusString(); } ?>
Additional Considerations
Solution for Extracting to Current Directory
To extract the ZIP file into the same directory where it resides, you can determine the absolute path to the file and specify that as the extraction target:
<?php $file = 'file.zip'; $path = pathinfo(realpath($file), PATHINFO_DIRNAME); $zip = new ZipArchive; $res = $zip->open($file); if ($res === TRUE) { $zip->extractTo($path); $zip->close(); echo "Extraction complete!"; } else { echo "Extraction failed: " . $zip->getStatusString(); } ?>
The above is the detailed content of How Can I Safely and Efficiently Extract ZIP Files Using PHP?. For more information, please follow other related articles on the PHP Chinese website!