php 用php解压文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8889025/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unzip a file with php
提问by BostonBB
I want to unzip a file and this works fine
我想解压缩一个文件,这很好用
system('unzip File.zip');
But I need to pass in the file name through the URL and can not get it to work, this is what I have.
但是我需要通过URL传入文件名并且无法使其工作,这就是我所拥有的。
$master = $_GET["master"];
system('unzip $master.zip');
What am I missing? I know it has to be something small and stupid I am overlooking.
我错过了什么?我知道它必须是我忽略的一些小而愚蠢的东西。
Thank you,
谢谢,
回答by rdlowrey
I can only assume your code came from a tutorial somewhere online? In that case, good job trying to figure it out by yourself. On the other hand, the fact that this code could actually be published online somewhere as the correct way to unzip a file is a bit frightening.
我只能假设您的代码来自在线某个地方的教程?在这种情况下,你自己想办法搞清楚就好了。另一方面,该代码实际上可以作为解压缩文件的正确方法在网上发布的事实有点令人恐惧。
PHP has built-in extensions for dealing with compressed files. There should be no need to use system
calls for this. ZipArchive
docsis one option.
PHP 具有用于处理压缩文件的内置扩展。应该没有必要为此使用system
调用。ZipArchive
文档是一种选择。
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$zip->extractTo('/myzips/extract_path/');
$zip->close();
echo 'woot!';
} else {
echo 'doh!';
}
Also, as others have commented, $HTTP_GET_VARS
has been deprecated since version 4.1 ... which was a reeeeeally long time ago. Don't use it. Use the $_GET
superglobal instead.
此外,正如其他人所评论的,$HTTP_GET_VARS
自 4.1 版以来已被弃用......这是很久以前的事了。不要使用它。改用$_GET
超全局变量。
Finally, be very careful about accepting whatever input is passed to a script via a $_GET
variable.
最后,在接受通过$_GET
变量传递给脚本的任何输入时要非常小心。
ALWAYS SANITIZE USER INPUT.
始终消毒用户输入。
UPDATE
更新
As per your comment, the best way to extract the zip file into the same directory in which it resides is to determine the hard path to the file and extract it specifically to that location. So, you could do:
根据您的评论,将 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";
}
回答by Aleksandar Vucetic
Please, don't do it like that (passing GET var to be a part of a system call). Use ZipArchiveinstead.
请不要那样做(传递 GET var 作为系统调用的一部分)。请改用ZipArchive。
So, your code should look like:
因此,您的代码应如下所示:
$zipArchive = new ZipArchive();
$result = $zipArchive->open($_GET["master"]);
if ($result === TRUE) {
$zipArchive ->extractTo("my_dir");
$zipArchive ->close();
// Do something else on success
} else {
// Do something on error
}
And to answer your question, your error is 'something $var something else' should be "something $var something else" (in double quotes).
为了回答你的问题,你的错误是“something $var something else”应该是“something $var something else”(双引号)。
回答by Rubyx
Using getcwd()
to extract in the same directory
使用getcwd()
在同一目录提取
<?php
$unzip = new ZipArchive;
$out = $unzip->open('wordpress.zip');
if ($out === TRUE) {
$unzip->extractTo(getcwd());
$unzip->close();
echo 'File unzipped';
} else {
echo 'Error';
}
?>
回答by Morteza Ziyae
I updated answer of @rdlowreyto a cleaner and better code, This will unzip a file into current directory using __DIR__
.
我将@rdlowrey 的答案更新为更清晰更好的代码,这将使用__DIR__
.
<?php
// config
// -------------------------------
// only file name + .zip
$zip_filename = "YOURFILENAME.zip";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' >
<title>Unzip</title>
<style>
body{
font-family: arial, sans-serif;
word-wrap: break-word;
}
.wrapper{
padding:20px;
line-height: 1.5;
font-size: 1rem;
}
span{
font-family: 'Consolas', 'courier new', monospace;
background: #eee;
padding:2px;
}
</style>
</head>
<body>
<div class="wrapper">
<?php
echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
echo "current dir: <span>" . __DIR__ . "</span><br>";
$zip = new ZipArchive;
$res = $zip->open(__DIR__ . '/' .$zip_filename);
if ($res === TRUE) {
$zip->extractTo(__DIR__);
$zip->close();
echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
} else {
echo '<p style="color:red;">Zip file not found!</p><br>';
}
?>
End Script.
</div>
</body>
</html>
回答by Samuel Kwame Antwi
Simply try this yourDestinationDiris the destination to extract to or remove -d yourDestinationDirto extract to root dir.
只需试试这个yourDestinationDir是提取到的目的地或删除-d yourDestinationDir以提取到根目录。
$master = 'someDir/zipFileName';
$data = system('unzip -d yourDestinationDir '.$master.'.zip');
回答by Faruque Ahamed Mollick
PHP has its own inbuilt class that can be used to unzip or extracts contents from a zip file. The class is ZipArchive. Below is the simple and basic PHP code that will extract a zip file and place it in a specific directory:
PHP 有自己的内置类,可用于从 zip 文件解压缩或提取内容。类是 ZipArchive。下面是简单和基本的 PHP 代码,它将提取一个 zip 文件并将其放置在特定目录中:
<?php
$zip_obj = new ZipArchive;
$zip_obj->open('dummy.zip');
$zip_obj->extractTo('directory_name/sub_dir');
?>
If you want some advance features then below is the improved code that will check if the zip file exists or not:
如果您想要一些高级功能,那么下面是改进的代码,用于检查 zip 文件是否存在:
<?php
$zip_obj = new ZipArchive;
if ($zip_obj->open('dummy.zip') === TRUE) {
$zip_obj->extractTo('directory/sub_dir');
echo "Zip exists and successfully extracted";
}
else {
echo "This zip file does not exists";
}
?>
回答by M_R_K
Simple PHP function to unzip. Please make sure you have zip extension installed on your server.
用于解压的简单 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;
}
}
回答by Varun Naharia
I updated answer of Morteza Ziaeemehrto a cleaner and better code, This will unzip a file provided within form into current directory using DIR.
我将Morteza Ziaeemehr 的答案更新为更清晰更好的代码,这将使用DIR将表单中提供的文件解压缩到当前目录中。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' >
<title>Unzip</title>
<style>
body{
font-family: arial, sans-serif;
word-wrap: break-word;
}
.wrapper{
padding:20px;
line-height: 1.5;
font-size: 1rem;
}
span{
font-family: 'Consolas', 'courier new', monospace;
background: #eee;
padding:2px;
}
</style>
</head>
<body>
<div class="wrapper">
<?php
if(isset($_GET['page']))
{
$type = $_GET['page'];
global $con;
switch($type)
{
case 'unzip':
{
$zip_filename =$_POST['filename'];
echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
echo "current dir: <span>" . __DIR__ . "</span><br>";
$zip = new ZipArchive;
$res = $zip->open(__DIR__ . '/' .$zip_filename);
if ($res === TRUE)
{
$zip->extractTo(__DIR__);
$zip->close();
echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
}
else
{
echo '<p style="color:red;">Zip file not found!</p><br>';
}
break;
}
}
}
?>
End Script.
</div>
<form name="unzip" id="unzip" role="form">
<div class="body bg-gray">
<div class="form-group">
<input type="text" name="filename" class="form-control" placeholder="File Name (with extension)"/>
</div>
</div>
</form>
<script type="application/javascript">
$("#unzip").submit(function(event) {
event.preventDefault();
var url = "function.php?page=unzip"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType:"json",
data: $("#unzip").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data.msg); // show response from the php script.
document.getElementById("unzip").reset();
}
});
return false; // avoid to execute the actual submit of the form
});
</script>
</body>
</html>
回答by user889030
you can use prepacked function
您可以使用预打包功能
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;
}
How to use it.
如何使用它。
if(unzip_file($file["name"],'uploads/')){
echo 'zip archive extracted successfully';
}else{
echo 'zip archive extraction failed';
}
回答by huync
Use below PHP code, with file name in the URL param "name"
使用下面的 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';
}
?>