我想解压缩一个文件,这工作得很好
system('unzip File.zip');
但我需要通过URL传递文件名,不能让它工作,这就是我所拥有的。
$master = $_GET["master"];
system('unzip $master.zip');
我错过了什么?我知道一定是我忽视的小而愚蠢的事情。
谢谢你!
我想解压缩一个文件,这工作得很好
system('unzip File.zip');
但我需要通过URL传递文件名,不能让它工作,这就是我所拥有的。
$master = $_GET["master"];
system('unzip $master.zip');
我错过了什么?我知道一定是我忽视的小而愚蠢的事情。
谢谢你!
当前回答
我只能假设你的代码来自网上的某个教程?在这种情况下,你靠自己解决问题做得很好。另一方面,这段代码实际上可以作为解压缩文件的正确方式在某个地方在线发布,这一事实有点令人恐惧。
PHP具有处理压缩文件的内置扩展。不需要为此使用系统调用。ZipArchivedocs是一种选择。
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$zip->extractTo('/myzips/extract_path/');
$zip->close();
echo 'woot!';
} else {
echo 'doh!';
}
另外,正如其他人所评论的那样,$HTTP_GET_VARS自4.1版本以来已被弃用…那是很久以前的事了。不要用它。请使用$_GET超全局变量。
最后,要非常小心地接受通过$_GET变量传递给脚本的任何输入。
总是清理用户输入。
更新
根据您的评论,将zip文件解压缩到其所在的同一目录的最佳方法是确定文件的硬路径,并将其专门解压缩到该位置。所以,你可以这样做:
// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';
// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($path);
$zip->close();
echo "WOOT! $file extracted to $path";
} else {
echo "Doh! I couldn't open $file";
}
其他回答
可以使用预包装函数
function unzip_file($file, $destination){
// create object
$zip = new ZipArchive() ;
// open archive
if ($zip->open($file) !== TRUE) {
return false;
}
// extract contents to destination directory
$zip->extractTo($destination);
// close archive
$zip->close();
return true;
}
如何使用它。
if(unzip_file($file["name"],'uploads/')){
echo 'zip archive extracted successfully';
}else{
echo 'zip archive extraction failed';
}
使用getcwd()在同一目录中进行解压缩
<?php
$unzip = new ZipArchive;
$out = $unzip->open('wordpress.zip');
if ($out === TRUE) {
$unzip->extractTo(getcwd());
$unzip->close();
echo 'File unzipped';
} else {
echo 'Error';
}
?>
简单的PHP解压缩函数。请确保您的服务器上安装了zip扩展。
/**
* Unzip
* @param string $zip_file_path Eg - /tmp/my.zip
* @param string $extract_path Eg - /tmp/new_dir_name
* @return boolean
*/
function unzip(string $zip_file_path, string $extract_dir_path) {
$zip = new \ZipArchive;
$res = $zip->open($zip_file_path);
if ($res === TRUE) {
$zip->extractTo($extract_dir_path);
$zip->close();
return TRUE;
} else {
return FALSE;
}
}
就用这个吧:
$master = $_GET["master"];
system('unzip' $master.'.zip');
在代码中,$master作为字符串传递,系统将寻找一个名为$master.zip的文件
$master = $_GET["master"];
system('unzip $master.zip'); `enter code here`
使用下面的PHP代码,文件名在URL参数“name”中
<?php
$fileName = $_GET['name'];
if (isset($fileName)) {
$zip = new ZipArchive;
$res = $zip->open($fileName);
if ($res === TRUE) {
$zip->extractTo('./');
$zip->close();
echo 'Extracted file "'.$fileName.'"';
} else {
echo 'Cannot find the file name "'.$fileName.'" (the file name should include extension (.zip, ...))';
}
}
else {
echo 'Please set file name in the "name" param';
}
?>