簡體   English   中英

如何使用PHP代碼在服務器(Linux)中解壓縮文件

[英]How to unzip file in server(linux) with php code

我嘗試了很多代碼,但是沒有用。

<?php
$file = $_GET['file'];

if (isset($file))
{
   echo "Unzipping " . $file . "<br>";
   if(system('unzip '. $file.' -d dirtounzipto ' ))
   {echo 'GGWP';}else{echo 'WTF';}

   exit;
}?>

我如何解壓縮服務器。 使用“系統”或“ shell_exec”代碼。

$zip_filename = "test.zip";
$zip_extract_path = "/";
try{
$zip_obj = new ZipArchive;
            if (file_exists($zip_filename)) {
                $zip_stat = $zip_obj->open($zip_filename);
                if ($zip_stat === TRUE) {
                    $res = $zip_obj->extractTo($zip_extract_path);
                    if ($res === false) {

                            throw new Exception("Error in extracting file on server.");

                    }
                    $zip_obj->close();


                } else {
                    throw new Exception("Error in open file");
                }
            } else {
                throw new Exception("zip file not found for extraction");
            }
}catch (Exception $e) {

    echo $e->getMessage();
}

請充分利用PHP的ZipArchive

<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
    $zip->extractTo('/my/destination/dir/');
    $zip->close();
    echo 'ok';
} else {
    echo 'failed';
}
?>

版本要求:PHP> = 5.2.0,PECL zip> = 1.1.0


更新要自動創建目標路徑,可以使用:

mkdir($path, 0755, true);

會自動創建所需的文件夾。

PHP具有用於處理壓縮文件的內置擴展。 為此,無需使用系統調用。 ZipArchive 文檔是一種選擇。

// 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);

//folder name as per zip file name
$foldername = basename($file, ".zip");

mkdir($foldername, 0755, true);
$path = $path . "/" . $foldername;

$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";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM