WebGraf » 2009.11.20 05:23

пишу
$arc->add("sss/file.jpg");
но архив остается без файла этого.
Как правильно добавить файл?

Gemorroj » 2009.11.20 09:26

полный код давай.

WebGraf » 2009.11.20 11:38

этот уже стер
использую другой
та же история
Добавлено спустя   1 минуту  8 секунд:

Код:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$createZip = new createZip;
$file_list = array();
recursiveReadDir (JAR_DATA_DIR, $file_list); // чтение директории с файлами
// Добавление файлов в архив
foreach($file_list as $c_file) {
if(is_dir($c_file)) { // создание директории в архиве
$c_file = str_replace(JAR_DATA_DIR, '', $c_file);
$createZip->addDirectory($c_file);
} else { // запись файлов
$fileContents = file_get_contents($c_file);
$c_file = str_replace(JAR_DATA_DIR, '', $c_file);
$createZip->addFile($fileContents, $c_file);
}
}

Добавлено спустя   3 минуты  1 секунду:
define ('JAR_DATA_DIR', JAR_ROOT_DIR.'resource/'); // папака с ресурсами JAVA приложения
Добавлено спустя   4 минуты  12 секунд:
инклудится отсюда CreateZipFile.class.php

Код:

1
span style="color: #0000BB"><?php/** * Class to dynamically create a zip file (archive) * * @author Rochak Chauhan */class createZip { var $compressedData = array(); var $centralDirectory = array(); // central directory var $endOfCentralDirectory = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record var $oldOffset = 0; /** * Function to create the directory where the file(s) will be unzipped * * @param $directoryName string * */ function addDirectory($directoryName) { $directoryName = str_replace("\\", "/", $directoryName); $feedArrayRow = "\x50\x4b\x03\x04"; $feedArrayRow .= "\x0a\x00"; $feedArrayRow .= "\x00\x00"; $feedArrayRow .= "\x00\x00"; $feedArrayRow .= "\x00\x00\x00\x00"; $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("v", strlen($directoryName) ); $feedArrayRow .= pack("v", 0 ); $feedArrayRow .= $directoryName; $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("V",0); $this -> compressedData[] = $feedArrayRow; $newOffset = strlen(implode("", $this->compressedData)); $addCentralRecord = "\x50\x4b\x01\x02"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x0a\x00"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x00\x00\x00\x00"; $addCentralRecord .= pack("V",0); $addCentralRecord .= pack("V",0); $addCentralRecord .= pack("V",0); $addCentralRecord .= pack("v", strlen($directoryName) ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $ext = "\x00\x00\x10\x00"; $ext = "\xff\xff\xff\xff"; $addCentralRecord .= pack("V", 16 ); $addCentralRecord .= pack("V", $this -> oldOffset ); $this -> oldOffset = $newOffset; $addCentralRecord .= $directoryName; $this -> centralDirectory[] = $addCentralRecord; } /** * Function to add file(s) to the specified directory in the archive * * @param $directoryName string * */ function addFile($data, $directoryName) { $directoryName = str_replace("\\", "/", $directoryName); $feedArrayRow = "\x50\x4b\x03\x04"; $feedArrayRow .= "\x14\x00"; $feedArrayRow .= "\x00\x00"; $feedArrayRow .= "\x08\x00"; $feedArrayRow .= "\x00\x00\x00\x00"; $uncompressedLength = strlen($data); $compression = crc32($data); $gzCompressedData = gzcompress($data); $gzCompressedData = substr( substr($gzCompressedData, 0, strlen($gzCompressedData) - 4), 2); $compressedLength = strlen($gzCompressedData); $feedArrayRow .= pack("V",$compression); $feedArrayRow .= pack("V",$compressedLength); $feedArrayRow .= pack("V",$uncompressedLength); $feedArrayRow .= pack("v", strlen($directoryName) ); $feedArrayRow .= pack("v", 0 ); $feedArrayRow .= $directoryName; $feedArrayRow .= $gzCompressedData; $feedArrayRow .= pack("V",$compression); $feedArrayRow .= pack("V",$compressedLength); $feedArrayRow .= pack("V",$uncompressedLength); $this -> compressedData[] = $feedArrayRow; $newOffset = strlen(implode("", $this->compressedData)); $addCentralRecord = "\x50\x4b\x01\x02"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x14\x00"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x08\x00"; $addCentralRecord .="\x00\x00\x00\x00"; $addCentralRecord .= pack("V",$compression); $addCentralRecord .= pack("V",$compressedLength); $addCentralRecord .= pack("V",$uncompressedLength); $addCentralRecord .= pack("v", strlen($directoryName) ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("V", 32 ); $addCentralRecord .= pack("V", $this -> oldOffset ); $this -> oldOffset = $newOffset; $addCentralRecord .= $directoryName; $this -> centralDirectory[] = $addCentralRecord; } /** * Fucntion to return the zip file * * @return zipfile (archive) */ function getZippedfile() { $data = implode("", $this -> compressedData); $controlDirectory = implode("", $this -> centralDirectory); return $data. $controlDirectory. $this -> endOfCentralDirectory. pack("v", sizeof($this -> centralDirectory)). pack("v", sizeof($this -> centralDirectory)). pack("V", strlen($controlDirectory)). pack("V", strlen($data)). "\x00\x00"; } /** * * Function to force the download of the archive as soon as it is created * * @param archiveName string - name of the created archive file */ function forceDownload($archiveName, $get_file_name) { $headerInfo = ''; if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } // Security checks if( $archiveName == "" ) { echo "<html><title>var Photo Directory - Download </title><body><BR><B>ERROR:</B> The download file was NOT SPECIFIED.</body></html>"; exit; } elseif ( ! file_exists( $archiveName ) ) { echo "<html><title>var Photo Directory - Download </title><body><BR><B>ERROR:</B> File not found.</body></html>"; exit; } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application/java-archive"); header("Content-Disposition: attachment; filename=".$get_file_name.";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($archiveName)); readfile("$archiveName"); }}?>
Gemorroj » 2009.11.20 11:49

Возможно, нет прав на перезапись zip архива.

WebGraf » 2009.11.20 11:53

короче неважно каким образом это сделать. главное вот что. архив создается и в первом и во втором случае. а добавить в архив немогу ничего
Добавлено спустя   1 минуту  31 секунду:
права уже дописывал скриптом и меняет на 777
до этого использовал другой скрипт, но при нагрузке он работает через раз
Добавлено спустя   3 минуты  31 секунду:
а все решил проблему
извиняюсь что потревожил. во втором случае действительно ошибка в правах была. а первый точно неработал. наверное ошибка в самом модуле PclZip была

Gemorroj » 2009.11.20 12:16

Нет, в PCLZIP ошибок быть не могло. Возможно, ты не указал папку для временных файлов, или не указал что временных файлов создавать не нужно. Никогда не списывай проблемы на чужие продукты, тем боее на такие известные.

WebGraf » 2009.11.20 12:28

видать это на сервере проблема. поставил этот скрипт. и 1 из 5 закачек прерывается. немогу понять что такое
Добавлено спустя   1 минуту  19 секунд:
ну с созданием архивов раньше неработал поэтому трудно

Gemorroj » 2009.11.20 13:00

попробуй заменить функцию forceDownload на эту http://wapinet.ru/forum/viewtopic.php?id=46

WebGraf » 2009.11.20 13:06

Код:

1
2
3
4
5
6
7
header('Accept-Ranges: bytes');
header('Content-Length: '.filesize(JARS_DIR.$fileName));
header('Content-Type: application/java-archive');
header('Connection: close');
header('Cache-control: no-cache');
header('Last-Modified: '.gmdate('r',time().' GMT'));
readfile(JARS_DIR.$fileName);

вот так отдаю файл

Gemorroj » 2009.11.20 13:09

set_time_limit(9999);

Fuelen » 2009.11.20 14:11

10, Или 0
Добавлено спустя   2 минуты  1 секунду:
Аффтар, юзай ZipArchive

Gemorroj » 2009.11.20 14:21

Fuelen, 0 лучше не использовать, т.к. это может привести к неубиваемому процессу.
И насчет ZipArchive тоже не соглашусь) У PclZip больше возможностей.

WebGraf » 2009.11.20 17:31

А что скажете на счет такого класа

Код:

1
span style="color: #0000BB"><?php/** * Class to dynamically create a zip file (archive) * * @author Rochak Chauhan */class createZip { var $compressedData = array(); var $centralDirectory = array(); // central directory var $endOfCentralDirectory = "\x50\x4b\x05\x06\x00\x00\x00\x00"; //end of Central directory record var $oldOffset = 0; /** * Function to create the directory where the file(s) will be unzipped * * @param $directoryName string * */ function addDirectory($directoryName) { $directoryName = str_replace("\\", "/", $directoryName); $feedArrayRow = "\x50\x4b\x03\x04"; $feedArrayRow .= "\x0a\x00"; $feedArrayRow .= "\x00\x00"; $feedArrayRow .= "\x00\x00"; $feedArrayRow .= "\x00\x00\x00\x00"; $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("v", strlen($directoryName) ); $feedArrayRow .= pack("v", 0 ); $feedArrayRow .= $directoryName; $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("V",0); $feedArrayRow .= pack("V",0); $this -> compressedData[] = $feedArrayRow; $newOffset = strlen(implode("", $this->compressedData)); $addCentralRecord = "\x50\x4b\x01\x02"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x0a\x00"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x00\x00\x00\x00"; $addCentralRecord .= pack("V",0); $addCentralRecord .= pack("V",0); $addCentralRecord .= pack("V",0); $addCentralRecord .= pack("v", strlen($directoryName) ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $ext = "\x00\x00\x10\x00"; $ext = "\xff\xff\xff\xff"; $addCentralRecord .= pack("V", 16 ); $addCentralRecord .= pack("V", $this -> oldOffset ); $this -> oldOffset = $newOffset; $addCentralRecord .= $directoryName; $this -> centralDirectory[] = $addCentralRecord; } /** * Function to add file(s) to the specified directory in the archive * * @param $directoryName string * */ function addFile($data, $directoryName) { $directoryName = str_replace("\\", "/", $directoryName); $feedArrayRow = "\x50\x4b\x03\x04"; $feedArrayRow .= "\x14\x00"; $feedArrayRow .= "\x00\x00"; $feedArrayRow .= "\x08\x00"; $feedArrayRow .= "\x00\x00\x00\x00"; $uncompressedLength = strlen($data); $compression = crc32($data); $gzCompressedData = gzcompress($data); $gzCompressedData = substr( substr($gzCompressedData, 0, strlen($gzCompressedData) - 4), 2); $compressedLength = strlen($gzCompressedData); $feedArrayRow .= pack("V",$compression); $feedArrayRow .= pack("V",$compressedLength); $feedArrayRow .= pack("V",$uncompressedLength); $feedArrayRow .= pack("v", strlen($directoryName) ); $feedArrayRow .= pack("v", 0 ); $feedArrayRow .= $directoryName; $feedArrayRow .= $gzCompressedData; $feedArrayRow .= pack("V",$compression); $feedArrayRow .= pack("V",$compressedLength); $feedArrayRow .= pack("V",$uncompressedLength); $this -> compressedData[] = $feedArrayRow; $newOffset = strlen(implode("", $this->compressedData)); $addCentralRecord = "\x50\x4b\x01\x02"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x14\x00"; $addCentralRecord .="\x00\x00"; $addCentralRecord .="\x08\x00"; $addCentralRecord .="\x00\x00\x00\x00"; $addCentralRecord .= pack("V",$compression); $addCentralRecord .= pack("V",$compressedLength); $addCentralRecord .= pack("V",$uncompressedLength); $addCentralRecord .= pack("v", strlen($directoryName) ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("v", 0 ); $addCentralRecord .= pack("V", 32 ); $addCentralRecord .= pack("V", $this -> oldOffset ); $this -> oldOffset = $newOffset; $addCentralRecord .= $directoryName; $this -> centralDirectory[] = $addCentralRecord; } /** * Fucntion to return the zip file * * @return zipfile (archive) */ function getZippedfile() { $data = implode("", $this -> compressedData); $controlDirectory = implode("", $this -> centralDirectory); return $data. $controlDirectory. $this -> endOfCentralDirectory. pack("v", sizeof($this -> centralDirectory)). pack("v", sizeof($this -> centralDirectory)). pack("V", strlen($controlDirectory)). pack("V", strlen($data)). "\x00\x00"; } /** * * Function to force the download of the archive as soon as it is created * * @param archiveName string - name of the created archive file */ function forceDownload($archiveName, $get_file_name) { $headerInfo = ''; if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off'); } // Security checks if( $archiveName == "" ) { echo "<html><title>var Photo Directory - Download </title><body><BR><B>ERROR:</B> The download file was NOT SPECIFIED.</body></html>"; exit; } elseif ( ! file_exists( $archiveName ) ) { echo "<html><title>var Photo Directory - Download </title><body><BR><B>ERROR:</B> File not found.</body></html>"; exit; } header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header("Content-Type: application/java-archive"); header("Content-Disposition: attachment; filename=".$get_file_name.";" ); header("Content-Transfer-Encoding: binary"); header("Content-Length: ".filesize($archiveName)); readfile("$archiveName"); }}?>
Gemorroj » 2009.11.20 19:55

скажу точно тоже самое. PclZip умеет много больше.

WebGraf » 2009.11.21 11:05

Код:

1
span style="color: #0000BB"><?phpreguire_once("pclzip.lib.php"); //подключаем библиотекуif (file_exists("archive.zip")) {unlink("archive.zip");} //удаляем старый файл архива$arc = new PclZip("archive.zip"); //создаем новый архив$arc->add("page.htm"); //добавляем файл page.htm в архив$d = opendir("img"); //добавляем также в архив все файлы из папки imgwhile ($f = readdir($d)) {if (!file_exists($f)) {$arc->add("./img/".$f);};}?>

вот так я пробовал создавать архив
уточните PclZip сделает это качественние чем клас выше или просто он больше всего умеет

Gemorroj » 2009.11.21 12:32

больше умеет. допустим, чтение папки, как сделано у тебя, в pclzip можно не делать, а просто указать папку которую нужно добавить.

WebGraf » 2009.11.21 12:40

WebGraf написал:

Код:

1
span style="color: #0000BB"><?phpreguire_once("pclzip.lib.php"); //подключаем библиотекуif (file_exists("archive.zip")) {unlink("archive.zip");} //удаляем старый файл архива$arc = new PclZip("archive.zip"); //создаем новый архив$arc->add("page.htm"); //добавляем файл page.htm в архив$d = opendir("img"); //добавляем также в архив все файлы из папки imgwhile ($f = readdir($d)) {if (!file_exists($f)) {$arc->add("./img/".$f);};}?>

1. Что в этом коде неверно или чего нехватает?
2. по скорости работы PclZip будет лучше?

Gemorroj » 2009.11.21 13:04

не reguire_once, а require_once

Код:

1
2
3
4
require 'pclzip.lib.php'; //подключаем библиотеку
 
$arc = new PclZip('archive.zip'); //создаем объект
$arc->create('page.htm,img', PCLZIP_OPT_REMOVE_ALL_PATH); // добавляем файлы

Добавлено спустя    48 секунд:
по скорости не знаю. в любом случае, по скорости будут быстрее встроенные в PHP функции для работы с архивами.

WebGraf » 2009.11.21 13:06

а ну это я исправил был у себя. код скопирован из страницы интрернета.
и вот архив создает, а добавить нехочет.
ну раз встроенные то нужно сервак ковырять
иду тогда сервак мучить

Gemorroj » 2009.11.21 13:08

WebGraf написал:

ну раз встроенные то нужно сервак ковырять

логики что-то не уловил..)
если файлы не добавляет, проверь пути к ним.

WebGraf » 2009.11.21 13:15

ну я так понял вы имели ввиду не модули которые я подключаю через риквае, а то что находится на сервере уже установленное. или я неправильно нопял?

Gemorroj » 2009.11.21 13:23

http://ru.php.net/zip

WebGraf » 2009.11.21 13:24

значит верно понял.
ZipArchive у меня не работает
модуля нету установленного

Gemorroj » 2009.11.21 13:31

выполни это var_dump(class_exists('ZipArchive'));

WebGraf » 2009.11.21 13:45

bool(false)

Gemorroj » 2009.11.21 13:56

=)) фигово)

WebGraf » 2009.11.21 14:05

эт я уже понял))
Добавлено спустя   5 минут  24 секунды:
По поводу PclZip. Нужно указывать путь к файлу от сервера или можно просто указать файл в текущей директории?

Gemorroj » 2009.11.21 14:44

как хочешь

WebGraf » 2009.11.21 16:07

уже установили Zip

Fuelen » 2009.11.21 16:57

Геморрой, ZipArchive удобнее. ИМХО :)

WebGraf » 2009.11.21 17:19

файлы добавляются. кроме этого
где здесь ошибка

Код:

1
2
3
4
5
$n = 'www';
$init_data = join(file($dir.'file'));
$init_data = str_replace('#NAME#', $n, $init_data);
$zip->addEmptyDir('folder');
$zip->addFile($init_data, 'folder/file');

Добавлено спустя   1 минуту  25 секунд:
все выполняется, кроме последней строки.
хотя есть прописать
$zip->addFile($dir.'file', 'folder/file');
все в норме

WebGraf » 2009.11.21 17:35

Пошел в обход. добавил файл и произвел манипуляцию с помощью addFromString

Gemorroj » 2009.11.21 18:22

$init_data = join(file($dir.'file')); - вот это маразм.
в мануале же ясно написано, что addFile добавляет данные из ФАЙЛА, а ты пихаешь туда строку с данными.

WebGraf » 2009.11.21 18:45

поэтому и неработало. ну главное выход нашел

WebGraf » 2009.11.21 20:00

И вообщето я недочитал мануал. Взял из другого скрипта и скопировал.