php로 파일 압축 풀기
파일을 압축 해제하고 싶은데 정상적으로 작동합니다.
system('unzip File.zip');
하지만 URL을 통해 파일명을 전달해야 하는데, 이것이 제가 가지고 있는 것입니다.
$master = $_GET["master"];
system('unzip $master.zip');
제가 무엇을 빠뜨리고 있나요?내가 간과하고 있는 작고 바보 같은 일이어야 한다는 걸 알아.
감사합니다.
당신의 코드는 온라인 어딘가에서 튜토리얼을 통해 나온 것 같군요?그렇다면 스스로 알아내려고 노력한 건 잘한 일이에요.한편, 이 코드가 실제로 파일의 압축을 푸는 올바른 방법으로 온라인 어딘가에 게시될 수 있다는 사실은 조금 두렵습니다.
PHP에는 압축 파일을 처리하기 위한 확장 기능이 내장되어 있습니다.사용할 필요가 없습니다.system
이 일을 요구하다. ZipArchive
docs 옵션 중 하나입니다.
$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";
}
그렇게 하지 마세요(GET var를 시스템 호출의 일부로 통과).대신 ZipArchive를 사용합니다.
따라서 코드는 다음과 같습니다.
$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
}
그리고 질문에 답하려면 "something $var something other"는 "something $var something other"여야 합니다(큰따옴표).
사용.getcwd()
같은 디렉토리에 추출하다
<?php
$unzip = new ZipArchive;
$out = $unzip->open('wordpress.zip');
if ($out === TRUE) {
$unzip->extractTo(getcwd());
$unzip->close();
echo 'File unzipped';
} else {
echo 'Error';
}
?>
@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>
단순히 your Destination Dir는 -d your Destination Dir를 추출하거나 삭제하여 root dir로 추출하는 수신처입니다.
$master = 'someDir/zipFileName';
$data = system('unzip -d yourDestinationDir '.$master.'.zip');
PHP에는 zip 파일의 압축을 풀거나 내용을 추출하는 데 사용할 수 있는 자체 클래스가 있습니다.클래스는 ZipArchive입니다.아래는 zip 파일을 추출하여 특정 디렉토리에 저장하는 단순하고 기본적인 PHP 코드입니다.
<?php
$zip_obj = new ZipArchive;
$zip_obj->open('dummy.zip');
$zip_obj->extractTo('directory_name/sub_dir');
?>
고급 기능이 필요한 경우 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";
}
?>
출처: PHP에서 zip 파일을 압축 해제하거나 압축을 푸는 방법
압축을 푸는 간단한 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;
}
}
Morteza Ziaeemhr의 답변을 보다 깨끗하고 좋은 코드로 업데이트했습니다.이것은 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>
그냥 바꿔요
system('unzip $master.zip');
이 분에게
system('unzip ' . $master . '.zip');
아니면 이거
system("unzip {$master}.zip");
사전 팩된 기능을 사용할 수 있습니다.
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';
}
URL 매개 변수 "name"에 파일 이름과 함께 아래 PHP 코드 사용
<?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';
}
?>
이것만 사용해 주세요.
$master = $_GET["master"];
system('unzip' $master.'.zip');
의 $master
은 '파일 검색', '파일 ', '파일 이라고 합니다.$master.zip
$master = $_GET["master"];
system('unzip $master.zip'); `enter code here`
언급URL : https://stackoverflow.com/questions/8889025/unzip-a-file-with-php
'programing' 카테고리의 다른 글
안드로이드 java.langVerify Error? (0) | 2022.09.18 |
---|---|
SQL DELETE with WHERE 조건에 대한 다른 테이블 참여 (0) | 2022.09.18 |
레지스트리 키 오류: Java 버전의 값은 '1.8'이지만 '1.7'이 필요합니다. (0) | 2022.09.18 |
PHP 코드에서 assert를 사용해야 합니까? (0) | 2022.09.18 |
자바에서는 작은따옴표와 큰따옴표가 다른가요? (0) | 2022.09.18 |