Home >Backend Development >PHP Tutorial >How to Safely Unzip Files from a URL in PHP?
File decompression in PHP
You want to decompress a file using PHP but are having difficulty when you try to pass the filename via the URL. Let’s dig into the problem and provide you with a solution.
Error analysis
You get the file name through $_GET, but the outdated $HTTP_GET_VARS is used in the code, PHP recommends using $_GET. Additionally, you are using system('unzip $master.zip') to unzip the file, which is unsafe as it requires a system call to be performed on the server.
Recommended Solution
PHP provides an extension specifically designed to handle compressed files, namely ZipArchive. It is recommended to use it like this:
$zip = new ZipArchive; $res = $zip->open('file.zip'); if ($res === TRUE) { $zip->extractTo('/myzips/extract_path/'); $zip->close(); echo '解压成功!'; } else { echo '解压失败!'; }
Handle relative paths
If you want the file to be extracted into the same directory as the file, you can determine the file of Absolute path and specify it as the decompression target like this:
$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 "解压成功! $file 已解压到 $path"; } else { echo "解压失败!无法打开 $file"; }
Security Tips
Always validate user input to prevent malicious code injection. Remember:
Always validate user input!
The above is the detailed content of How to Safely Unzip Files from a URL in PHP?. For more information, please follow other related articles on the PHP Chinese website!