开发者

Using ZipArchive Class in PHP

开发者 https://www.devze.com 2023-03-25 18:58 出处:网络
I am using this code to read a protected directory (username&password) contents called (protect).

I am using this code to read a protected directory (username&password) contents called (protect).

<?php
require_once("admin/global.inc.php");

// increase script timeout value
ini_set('max_execution_time', 300);

//Generate a new flag
$random = (rand(000000,999999));
$date = date("y-m-d");

// create object
$zip = new ZipArchive();

// open archive 
if ($zip->open("$date-$random.zip", ZIPARCHIVE::CREATE) !== TRUE) {
    die ("Could not open archive");
}

// initialize an iterator
// pass it the directory to be processed
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("protect/")); //check question #2

// iterate over the directory
// add each file found to the archive
foreach ($iterator as $key=>$value) {
        if ($key != 'protect/.htaccess')
                {
    $zip->addFile(realpath($key), $key) or die ("ERROR: Could not add file: $key");        
$query="INSERT INTO `archives_logs` (`id`, `file`, `flag`, `date`) VALUES (NULL, '$key', '$random', '$date')";
            $query_result = mysql_query ($query);
                }
}

// close and save archive
$zip->close();
echo "Archive created successfully.";    
?>

If I place my code file in a location differerent than the protected directory location, i have to change the path of the directory to be compressed which is fine, BUT the problem is that all directories in the path are included in the Zip Archive. So if open the compressed file i get: www/username/public_html/etc...

Here is the directories strcuture: www/protect/(files to be compressed here) www/compress_code.php (here is my current code file)

The path that I wish to place my code file in is: www/protect/admin/files/compress_code.php

Q1) How do I keep my code file in the last mentioned location WITHOUT including the path in my ZipArchive file?

Q2) When my code is in the same location of the directory to be compressed, and when i open the compressed file i see, protect/(the files). Can I add only the content of protect directory in the Zip 开发者_JS百科Archive without inclduing the directory itself?


It's pretty simple:

  1. Store the target path in a variable.
  2. Remove target path from the localname before adding the file.

Like this:

$flags = FilesystemIterator::KEY_AS_PATHNAME | FilesystemIterator::SKIP_DOTS;
$target = 'protect/';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($target, $flags));

foreach ($iterator as $key=>$value) {
    if ($key != "{$target}.htaccess")
    {
        $localname = substr($key, strlen($target));
        $zip->addFile($key, $localname) or die ("ERROR: Could not add file: $key");
    }
}

This should actually answers both of your questions.

0

精彩评论

暂无评论...
验证码 换一张
取 消