Привет! В этой записи я опишу как производится работа с Zip в PHP.
Рассмотрим некоторые случаи использования Zip в PHP:
- архивирование файла
- архивирование папки
- распаковка zip архива
Для работы представленных примеров должно быть включено расширение php_zip.
Архивирование файла в Zip на PHP
Создаем архив, добавляем в него файлы, а затем закрываем архив.
$zip = new ZipArchive(); $zip->open('path/to/zipfile.zip', ZipArchive::CREATE); $zip->addFile('some-file.pdf', 'subdir/filename.pdf'); $zip->addFile('another-file.xlxs', 'filename.xlxs'); $zip->close();
Архивирование папки в Zip на PHP
Для архивирования папки можно воспользоваться такой функцией:
public static function zip($source, $destination) { if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); if (!$zip->open($destination, ZIPARCHIVE::CREATE)) { return false; } $source = str_replace('\', DIRECTORY_SEPARATOR, realpath($source)); $source = str_replace('/', DIRECTORY_SEPARATOR, $source); if (is_dir($source) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); foreach ($files as $file) { $file = str_replace('\', DIRECTORY_SEPARATOR, $file); $file = str_replace('/', DIRECTORY_SEPARATOR, $file); if ($file == '.' || $file == '..' || empty($file) || $file == DIRECTORY_SEPARATOR) { continue; } // Ignore "." and ".." folders if (in_array(substr($file, strrpos($file, DIRECTORY_SEPARATOR) + 1), array('.', '..'))) { continue; } $file = realpath($file); $file = str_replace('\', DIRECTORY_SEPARATOR, $file); $file = str_replace('/', DIRECTORY_SEPARATOR, $file); if (is_dir($file) === true) { $d = str_replace($source . DIRECTORY_SEPARATOR, '', $file); if (empty($d)) { continue; } $zip->addEmptyDir($d); } elseif (is_file($file) === true) { $zip->addFromString(str_replace($source . DIRECTORY_SEPARATOR, '', $file), file_get_contents($file)); } else { // do nothing } } } elseif (is_file($source) === true) { $zip->addFromString(basename($source), file_get_contents($source)); } return $zip->close(); }
Указываем папку и куда положить архив:
zip('/folder/to/compress/', './compressed.zip');
Распаковка Zip архива на PHP
Указываем файл архива и папку для его распаковки:
$zip = new ZipArchive; $res = $zip->open('file.zip'); if ($res === TRUE) { $zip->extractTo('/myzips/extract_path/'); $zip->close(); }
Работа с Zip в PHP не составит трудностей, особенно для наличии этой статьи ? Расширение php_zip облегчает жизнь разработчикам, которые столкнулись с необходимостью реализовать работу с архивами в PHP скриптах.
2465
andy-blog.ru
Я могу только предположить, что ваш код появился из учебника где-то в Интернете? В этом случае, хорошая работа, пытаясь понять это самостоятельно.
x421; другой стороны, тот факт, что этот код действительно может быть опубликован в Интернете, как правильный способ распаковать файл, немного пугает.
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!'; }
Кроме того, как прокомментировали другие, $HTTP_GET_VARS
был устаревшим с версии 4.1 …, который был reeeeeally давно. Не используйте его. Вместо этого используйте $_GET
.
Наконец, будьте очень осторожны, принимая любой вход, передаваемый скрипту через переменную $_GET
.
ОБНОВИТЬ
Согласно вашему комментарию, лучший способ извлечь zip-файл в тот же каталог, в котором он находитс.
E;жения. Итак, вы можете сделать:
// 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"; }
ruphp.com
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.
p has builtin extensions for dealing $filename = $zip>getnameindex($i); $fileinfo = pathinfo($filename); copy(«zip «.$path.»#».$filename, «/your/new/destination/».$fileinfo[‘basename’]); } $zip>close(); } ?> on a side note, you can also use $_files[‘userfile’][‘tmp_name’] as the $path for an uploaded zip so you never have to move it or extract a uploaded zip it detects .zip rar tar.gz gz archives and let you choose which one to extract (if there are multiple archives available). as of version .. it also supports creating archives. it’s handy if you do not have shell access. e.g. if you want to upload a lot of files (php framework or image collection) as archive because it is much
Vu sur exclutips.com
Vu sur img.raymond.cc
Vu sur 4.bp.blogspot.com
github is where people build software. more than million people use github to discover, fork, and contribute to over million projects. github is where people build software. more than million people use github to discover, fork, and contribute to over million projects. <?php. the unzip script. this script lists all of the .zip files in a directory. and allows you to select one to unzip. unlike cpanel’s file. manager, it _will_ overwrite existing files. / to use this script, ftp or paste this script into a file in the directory. with the .zip you want to unzip. then point your web browser at this.
Vu sur 000webhost.com
Vu sur attec.at
Vu sur net2ftp.com
if you migrate from other hosting to best hosting this will be useful open(‘test.zip’) === true) { $zip>extractto(‘/my/destination/dir/’); $zip>close(); echo ‘ok’; }… a video tutorial showing you how to use php to extract files that are inside a zip archive. abell from this tutorial you’ll learn how to unzip files on your server using unzipper.php script.first, you need to download unzipper.php script. upload your zipped file to the server (in my case, “wpmu.zip”). edit unzip.php to point to your file (download unzip.php above). upload unzip.php to the same folder as your zipped file. open a browser and point it to mydo/unzip.php (make sure to change “mydo” to your do).

Vu sur coursesweb.net
Vu sur pro-wordpress.ru
Vu sur hscripts.com
Vu sur kivabe.com
www.expert-php.fr
К сожалению, не все хостинги дают доступ по ssh. При его наличии жизнь становится простой и прекрасной: используя клиент winscp можно упаковывать-распаковывать tgz-архивы одним кликом мыши. Однако…
Есть два пути:
1. Путь простой, с использованием системных команд.
Закачиваем zip-архив, рядом с ним (в той же папке) помещаем php-скрипт следующего содержания
<?php
echo exec('unzip file.zip');
?>
Естественно, можно все это хозяйство хранить в разных папках, просто тогда придется указывать путь к file.zip относительно запускаемого скрипта.
2. Путь сложный, но универсальный.
Используем библиотеку PclZip (сайт разработчиков). Русскоязычное описание PclZip
В одну папку с библиотекой помещаем архив archive.zip и скрипт распаковки:
<?php
require_once('pclzip.lib.php');
$archive = new PclZip("archive.zip");
if ($archive->extract() == 0) {
die("Error : ".$archive->errorInfo(true));
}
?>
Файлы будут извлечены в ту же папку. Как изменить папку назначения описано по ссылке выше.
Для создания архива используем ту же библиотеку, передавая ей в список архивируемых файлов как строку: «file1.php,file2.php,file3.php» (без пробелов). Если файлов много, можно строить их список автоматически, использую скрипт:
<?php
require_once('pclzip.lib.php');//подключаем библиотеку
$files = glob('{,.ht}*', GLOB_BRACE);//получаем массив всех файлов в текущей папке, исключая .htaccess, .htpasswd
$s = array();
$aForbiddenNames = array('pclzip.lib.php','cgi-bin','zip.php','unzip.php');//указываем файлы, какие не следует включать в архив
//исключаем из массива файлов запрещенные
foreach($files as $file){
if(in_array($file,$aForbiddenNames)) continue;
$s[] = $file;
}
$s = implode(',', $s);//превращаем массив в строку
$archive = new PclZip('archive.zip');
$v_list = $archive->create($s);//создаем архив, передавая строку со списком файлов для архивации
if ($v_list == 0) {die("Error : ".$archive->errorInfo(true)); }
?>
umi-cms.spb.su
As you have seen earlier, I have posted an article How to create a ZIP file using PHP and MySQL. Today we are going to extract or unzip files from ZIP archieve using PHP. Using ZIP archieve you can store multiple files. You can create a .zip archieve files using compression or without compression. Suppose you have a ZIP archieve which contains multiple files in it and you want to unzip/extract all the files which exists inside the ZIP archieve to a different location. Below are the steps how to do it in php.
function.php
This file contains few functions which we will use later.
<?php /*This function will check whether files are valid files*/ function ValidFileExtension(){ return array('png','jpg','jpeg','gif'); } /*Read all folder and files*/ function ReadAllFolderAndFiles($dir,&$file_list){ $dir_and_files = scandir($dir); foreach($dir_and_files as $df){ if($df != '.' && $df != '..'){ if(is_file($dir.'/'.$df) && $df!='Thumbs.db'){ $FileExt=getFileExtension($dir.'/'.$df); if(!in_array($FileExt,ValidFileExtension())){ $file_list["INVALID_FILE"][]=$dir.'/'.$df; }else{ $file_list["VALID_FILE"][]=$dir.'/'.$df; } } if(is_dir($dir.'/'.$df)) ReadAllFolderAndFiles($dir.'/'.$df,$file_list); } } return $file_list; } /*This function will return zip extension file name*/ function getFileExtension($file_name){ if(trim($file_name)!=''){ $ext_part= pathinfo($file_name); $ext = strtolower($ext_part["extension"]); return $ext; } } /*This function will check whether uploaded file is a valid zip file*/ function IsValidZipFile($file_path) { if($file_path!=''){ $zip = zip_open($file_path); if (is_resource($zip)) { zip_close($zip); //Close the zip file after checking return true; }else{ return false; } } } /*This function will Delete directory and all files under it recursively*/ function RecursiveDeleteDirectory($dir) { if(is_dir($dir)){ foreach (scandir($dir) as $file) { if ($file != '.' && $file != '..') { if(is_dir($dir.'/'.$file)) { RecursiveDeleteDirectory($dir.'/'.$file); }else{ if(is_file($dir.'/'.$file) && file_exists($dir.'/'.$file)){ unlink($dir.'/'.$file); } } } } return rmdir($dir); } } /*This function will removes all files from the folder*/ function DeleteAllFiles($dir){ $files = glob($dir.'*');// get all file names inside this directory foreach($files as $file){ if(is_file($file)) unlink($file); // delete file } } ?>
The function.php file contains 6 functions. Lets describe in details. ValidFileExtension() function will validate those files extension which are defined inside this function. ReadAllFolderAndFiles() function will read all the folders and the files which are located under the ZIP archieve and if those have valid extensions then it stores them in the VALID_FILE array variable else stores all invalid files in the INVALID_FILE array variable and finally this function will return an array. Then the getFileExtension() function returns the file extension. IsValidZipFile() function checks whether uploaded ZIP is a valid ZIP archieve file. RecursiveDeleteDirectory() function recursively deletes all files and folders. Finally DeleteAllFiles function will delete all files from the given path.
index.php
This is a demo page to show how to validate the form and use the extract function.
<?php $ShowError=array(); $TotalUploadFiles=0; if($_SERVER['REQUEST_METHOD']=='POST'){ if (extension_loaded('zip')) { //validation if(isset($_FILES['zip_file']) && (trim($_FILES['zip_file']['tmp_name'])=='')){ $ShowError[]="Upload zip file."; }elseif(IsValidZipFile($_FILES["zip_file"]['tmp_name'])==false){ $ShowError[]="Please upload zip file only."; } if(count($ShowError)<=0){ //This should be absoluth folder path where zip file will upload $UploadZipFolderPath=$_SERVER["DOCUMENT_ROOT"]."/site/script/unzip/upload/"; $file_destination=$UploadZipFolderPath.$_FILES['zip_file']['name']; if(move_uploaded_file($_FILES['zip_file']['tmp_name'],$file_destination)){ $ExtractFolderName=$UploadZipFolderPath.basename($file_destination,".".getFileExtension($file_destination)); $file_list=array(); $ExtractFolderPath=$_SERVER["DOCUMENT_ROOT"]."/site/script/unzip/extract/"; $zip = new ZipArchive; if ($zip->open($file_destination) === TRUE) { $zip->extractTo($UploadZipFolderPath); $zip->close(); chmod($file_destination, 0777); unlink($file_destination); $UploadedFileList=ReadAllFolderAndFiles($UploadZipFolderPath,$file_list); $TotalUploaded=count($UploadedFileList); if($TotalUploaded>0){ //UnSuccess Uploaded Files $UnSuccessUploaded=$UploadedFileList["INVALID_FILE"]; $TotalUnSuccess=count($UnSuccessUploaded); $UnSuccessArr=array(); if($TotalUnSuccess>0){ $ct=0; while($ct<$TotalUnSuccess){ $UnSuccessArr[]=basename($UnSuccessUploaded[$ct]); $ct++; } if(count($UnSuccessArr)>0){ $ShowError[]="These file(s) ". implode(',',$UnSuccessArr) . " are not a valid image file. Remove these files and upload again."; } }else{ $SuccessUploaded=$UploadedFileList["VALID_FILE"]; $TotalSuccess=count($SuccessUploaded); if($TotalSuccess>0){ $ct=0; while($ct<$TotalSuccess){ copy($SuccessUploaded[$ct],$ExtractFolderPath.basename($SuccessUploaded[$ct])); $ct++; $TotalUploadFiles++; } } } if(!is_dir($ExtractFolderName)){ DeleteAllFiles($UploadZipFolderPath); }else{ RecursiveDeleteDirectory($ExtractFolderName); } } } } } }else{ $ShowError[]="Zip extension is not loaded."; } } ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>How to extract ZIP file in PHP</title> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <table width="100%" border="0"> <?php if(count($ShowError)>0 || $TotalUploadFiles>0){?> <tr> <td colspan="2" align="center"> <?php if(count($ShowError)>0){ echo implode("n",$ShowError); }else if($TotalUploadFiles>0){ $TotalUploadFiles . ' files uploaded successfully.'; } ?> </td> </tr> <?php } ?> <tr> <td width="45%" align="right">Zip File: </td> <td width="55%" align="left"><input type="file" name="zip_file" /></td> </tr> <tr> <td colspan="2" align="center"><input type="submit" value="Upload" /></td> </tr> </table> </form> </body> </html>
The above code contains a simple HTML form. If the file is uploaded and extracted successfully then it displays the success message else it will show all error messages. Once user submitted the form extension_loaded() function checks whether ZIP extension module is installed or not. If it is not installed then it will display an error else execute the next block of code. Next it checks whether uploaded file is a valid zip file. If there is no error it will execute next block of code. Set your absolute path on this variable i.e $UploadZipFolderPath where temporaryly zip file will stored. Once zip file will be uploaded in the destination folder the $ExtractFolderName variable will return the zip folder name without the .zip extension.
Next define your folder name where all extracted files will store on this variable i.e $ExtractFolderPath. Then the ZipArchive constructor is called and open() method of zip archieves opens an archieve for writing,reading or modifying. The most important thing is extractTo() function. This function extract all files to the destination folder. Then close() method closes the active archieve. After successfull extraction of the zip file, set file permission to 0777 using chmod() function so the script can delete the zip archieve from the folder. Here I have written this 2 line of codes because I don’t want to store the zip archieve once it is succefully extracted. Delete the zip files so the server gets some space.
Then ReadAllFolderAndFiles() function is used which is defined in the function.php file. It accepts 2 parameters, first one is the file path of the folder where all your zip files uploaded, second parameter is reference array variable. Next, after reading all files using this function it returns 2 array variables as I have discussed earlier. If there is any invalid file then it stores errors in this variable $ShowError else it copies all the files to the destination folder.
Finally DeleteAllFiles() and RecursiveDeleteDirectory() functions are used. You can create your zip archieve in 2 ways. Either you add all the files inside the zip archive without any folder or first you create a folder then add all files in it and finally create the zip archieve. DeleteAllFiles() function deletes all files if you have create the zip without any folder and RecursiveDeleteDirectory() function deletes all files and folders recursively.
www.ewebtutorials.com
I updated answer of Morteza Ziaeemehr to a cleaner and better code, This will unzip a file provided within form into current directory using 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>
stackoverflow.com
function preflightCheck() { require_once 'modules/UpgradeWizard/uw_files.php'; global $sugar_config; global $mod_strings; global $sugar_version; if (!isset($sugar_version) || empty($sugar_version)) { require_once './sugar_version.php'; } unset($_SESSION['rebuild_relationships']); unset($_SESSION['rebuild_extensions']); // don't bother if are rechecking $manualDiff = array(); if (!isset($_SESSION['unzip_dir']) || empty($_SESSION['unzip_dir'])) { logThis('unzipping files in upgrade archive...'); $errors = array(); $base_upgrade_dir = $sugar_config['upload_dir'] . "/upgrades"; $base_tmp_upgrade_dir = "{$base_upgrade_dir}/temp"; $unzip_dir = ''; //Following is if User logged out unexpectedly and then logged into UpgradeWizard again. //also come up with mechanism to read from upgrade-progress file. if (!isset($_SESSION['install_file']) || empty($_SESSION['install_file']) || !is_file($_SESSION['install_file'])) { if (file_exists(clean_path($base_tmp_upgrade_dir)) && ($handle = opendir(clean_path($base_tmp_upgrade_dir)))) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { //echo $base_tmp_upgrade_dir."/".$file.'</br>'; if (is_file($base_tmp_upgrade_dir . "/" . $file . "/manifest.php")) { require_once $base_tmp_upgrade_dir . "/" . $file . "/manifest.php"; $package_name = $manifest['copy_files']['from_dir']; //echo file_exists($base_tmp_upgrade_dir."/".$file."/".$package_name).'</br>'; if (file_exists($base_tmp_upgrade_dir . "/" . $file . "/" . $package_name) && file_exists($base_tmp_upgrade_dir . "/" . $file . "/scripts") && file_exists($base_tmp_upgrade_dir . "/" . $file . "/manifest.php")) { //echo 'Yeah this the directory '. $base_tmp_upgrade_dir."/".$file; $unzip_dir = $base_tmp_upgrade_dir . "/" . $file; if (file_exists($sugar_config['upload_dir'] . '/upgrades/patch/' . $package_name . '.zip')) { $_SESSION['install_file'] = $sugar_config['upload_dir'] . '/upgrades/patch/' . $package_name . '.zip'; break; } } } } } } } if (!isset($_SESSION['install_file']) || empty($_SESSION['install_file'])) { unlinkTempFiles(); resetUwSession(); echo 'Upload File not found so redirecting to Upgrade Start '; $redirect_new_wizard = $sugar_config['site_url'] . '/index.php?module=UpgradeWizard&action=index'; echo '<form name="redirect" action="' . $redirect_new_wizard . '" method="POST">'; $upgrade_directories_not_found = <<<eoq t<table cellpadding="3" cellspacing="0" border="0"> tt<tr> ttt<th colspan="2" align="left"> tttt<span class='error'><b>'Upload file missing or has been deleted. Refresh the page to go back to UpgradeWizard start'</b></span> ttt</th> tt</tr> t</table> eoq; $uwMain = $upgrade_directories_not_found; return ''; } $install_file = urldecode($_SESSION['install_file']); $show_files = true; if (empty($unzip_dir)) { $unzip_dir = mk_temp_dir($base_tmp_upgrade_dir); } $zip_from_dir = "."; $zip_to_dir = "."; $zip_force_copy = array(); if (!$unzip_dir) { logThis('Could not create a temporary directory using mk_temp_dir( $base_tmp_upgrade_dir )'); die($mod_strings['ERR_UW_NO_CREATE_TMP_DIR']); } //double check whether unzipped . if (file_exists($unzip_dir . "/scripts") && file_exists($unzip_dir . "/manifest.php")) { //already unzipped } else { unzip($install_file, $unzip_dir); } // assumption -- already validated manifest.php at time of upload require_once "{$unzip_dir}/manifest.php"; if (isset($manifest['copy_files']['from_dir']) && $manifest['copy_files']['from_dir'] != "") { $zip_from_dir = $manifest['copy_files']['from_dir']; } if (isset($manifest['copy_files']['to_dir']) && $manifest['copy_files']['to_dir'] != "") { $zip_to_dir = $manifest['copy_files']['to_dir']; } if (isset($manifest['copy_files']['force_copy']) && $manifest['copy_files']['force_copy'] != "") { $zip_force_copy = $manifest['copy_files']['force_copy']; } if (isset($manifest['version'])) { $version = $manifest['version']; } if (!is_writable("config.php")) { return $mod_strings['ERR_UW_CONFIG']; } $_SESSION['unzip_dir'] = clean_path($unzip_dir); $_SESSION['zip_from_dir'] = clean_path($zip_from_dir); //logThis('unzip done.'); } else { $unzip_dir = $_SESSION['unzip_dir']; $zip_from_dir = $_SESSION['zip_from_dir']; } //check if $_SESSION['unzip_dir'] and $_SESSION['zip_from_dir'] exist if (!isset($_SESSION['unzip_dir']) || !file_exists($_SESSION['unzip_dir']) || !isset($_SESSION['install_file']) || empty($_SESSION['install_file']) || !file_exists($_SESSION['install_file'])) { //redirect to start unlinkTempFiles(); resetUwSession(); echo 'Upload File not found so redirecting to Upgrade Start '; $redirect_new_wizard = $sugar_config['site_url'] . '/index.php?module=UpgradeWizard&action=index'; echo '<form name="redirect" action="' . $redirect_new_wizard . '" method="POST">'; $upgrade_directories_not_found = <<<eoq t<table cellpadding="3" cellspacing="0" border="0"> tt<tr> ttt<th colspan="2" align="left"> tttt<span class='error'><b>'Upload file missing or has been deleted. Refresh the page to go back to UpgradeWizard start'</b></span> ttt</th> tt</tr> t</table> eoq; $uwMain = $upgrade_directories_not_found; return ''; } //copy minimum required files fileCopy('include/utils/sugar_file_utils.php'); if (file_exists('include/utils/file_utils.php')) { } $upgradeFiles = findAllFiles(clean_path("{$unzip_dir}/{$zip_from_dir}"), array()); $cache_html_files = array(); if (is_dir("{$GLOBALS['sugar_config']['cache_dir']}layout")) { //$cache_html_files = findAllFilesRelative( "cache/layout", array()); } // get md5 sums $md5_string = array(); if (file_exists(clean_path(getcwd() . '/files.md5'))) { require clean_path(getcwd() . '/files.md5'); } // file preflight checks logThis('verifying md5 checksums for files...'); foreach ($upgradeFiles as $file) { if (in_array(str_replace(clean_path("{$unzip_dir}/{$zip_from_dir}") . "/", '', $file), $uw_files)) { continue; } // skip already loaded files if (strpos($file, '.md5')) { continue; } // skip md5 file // normalize file paths $file = clean_path($file); // check that we can move/delete the upgraded file if (!is_writable($file)) { $errors[] = $mod_strings['ERR_UW_FILE_NOT_WRITABLE'] . ": " . $file; } // check that destination files are writable $destFile = getcwd() . str_replace(clean_path($unzip_dir . '/' . $zip_from_dir), '', $file); if (is_file($destFile)) { // of course it needs to exist first... if (!is_writable($destFile)) { $errors[] = $mod_strings['ERR_UW_FILE_NOT_WRITABLE'] . ": " . $destFile; } } /////////////////////////////////////////////////////////////////////// //// DIFFS // compare md5s and build up a manual merge list $targetFile = clean_path("." . str_replace(getcwd(), '', $destFile)); $targetMd5 = '0'; if (is_file($destFile)) { if (strpos($targetFile, '.php')) { // handle PHP files that were hit with the security regex $fp = ''; if (function_exists('sugar_fopen')) { $fp = sugar_fopen($destFile, 'r'); } else { $fp = fopen($destFile, 'r'); } $filesize = filesize($destFile); if ($filesize > 0) { $fileContents = fread($fp, $filesize); $targetMd5 = md5($fileContents); } } else { $targetMd5 = md5_file($destFile); } } if (isset($md5_string[$targetFile]) && $md5_string[$targetFile] != $targetMd5) { logThis('found a file with a differing md5: [' . $targetFile . ']'); $manualDiff[] = $destFile; } //// END DIFFS /////////////////////////////////////////////////////////////////////// } logThis('md5 verification done.'); $errors['manual'] = $manualDiff; return $errors; }
hotexamples.com
Зачем архивировать данные на хостинге
В файловом менеджере большинства хостеров есть кнопка «распаковать архив». Но если вам посчастливилось столкнуться с хостингом, у которого нет такой функции (а то и вообще не файлового менеджера), не отчаивайтесь и читайте дальше.
Как архивировать файлы на сервере: php скрипт – Архиватор
PHP скрипт Архиватор создан специально для того, чтобы архивировать файлы на хостинге, который не имеет штатных средств для этих целей. Скрипт очень прост в использовании и удобен.
- Скачайте архив со скриптом с моего блога по ссылке. Извлеките файлы из архива.
- Скопируйте файлы add_to_archive.php и pclzip.lib.php по ftp на хостинг, расположите их в папке, которую вам нужно заархивировать.
- Установите атрибуты для папки 777
- Откройте в браузере файл архиватора: https://www.ваш_сайт/ваша_папка/add_to_archive.php
- Скачайте получившийся архив на свой компьютер. Готово!
pro-wordpress.ru