CakeFest 2024: The Official CakePHP Conference

Примеры

Также смотрите примеры по ссылке rar:// wrapper.

Пример #1 Декомпрессия на лету

<?php

if (!array_key_exists("i", $_GET) || !is_numeric($_GET["i"]))
die(
"Индекс не указан или не числовой");
$index = (int) $_GET["i"];

$arch = RarArchive::open("example.rar");
if (
$arch === FALSE)
die(
"Невозможно открыть example.rar");

$entries = $arch->getEntries();
if (
$entries === FALSE)
die(
"Невозможно получить записи");

if (!
array_key_exists($index, $entries))
die(
"Нет такого индекса: $index");

$orfilename = $entries[$index]->getName(); //Кодировка UTF-8

$filesize = $entries[$index]->getUnpackedSize();

/* Вы можете здесь проверить константу HTTP_IF_MODIFIED_SINCE и сравнить с
* $entries[$index]->getFileTime(). Также возможно отослать заголовок
* "Last modified" */

$fp = $entries[$index]->getStream();
if (
$fp === FALSE)
die(
"Невозможно открыть файл с индексом $index внутри архива.");

$arch->close(); // Больше не нужен. Поток является независимым

function detectUserAgent() {
if (!
array_key_exists('HTTP_USER_AGENT', $_SERVER))
return
"Other";

$uas = $_SERVER['HTTP_USER_AGENT'];
if (
preg_match("@Opera/@", $uas))
return
"Opera";
if (
preg_match("@Firefox/@", $uas))
return
"Firefox";
if (
preg_match("@Chrome/@", $uas))
return
"Chrome";
if (
preg_match("@MSIE ([0-9.]+);@", $uas, $matches)) {
if (((float)
$matches[1]) >= 7.0)
return
"IE";
}

return
"Other";
}

/*
* Действуют 3 опции:
* - Для FF и Opera, с поддержкой RFC 2231, используется этот формат.
* - Для IE и Chrome, используется attwithfnrawpctenclong
* (http://greenbytes.de/tech/tc2231/#attwithfnrawpctenclong)
* - Для других браузеров, перекодируется в ISO-8859-1, если возможно
*/
$formatRFC2231 = 'Content-Disposition: attachment; filename*=UTF-8\'\'%s';
$formatDef = 'Content-Disposition: attachment; filename="%s"';

switch (
detectUserAgent()) {
case
"Opera":
case
"Firefox":
$orfilename = rawurlencode($orfilename);
$format = $formatRFC2231;
break;

case
"IE":
case
"Chrome":
$orfilename = rawurlencode($orfilename);
$format = $formatDef;
break;
default:
if (
function_exists('iconv'))
$orfilename =
@
iconv("UTF-8", "ISO-8859-1//TRANSLIT", $orfilename);
$format = $formatDef;
}

header(sprintf($format, $orfilename));
//Невозможна дальнейшая отсылка сообщений об ошибках (заголовки уже отправлены)

//Замена на реальный content type, возможно определённый по расширению файла
$contentType = "application/octet-stream";
header("Content-Type: $contentType");

header("Content-Transfer-Encoding: binary");

header("Content-Length: $filesize");

if (
$_SERVER['REQUEST_METHOD'] == "HEAD")
die();

while (!
feof($fp)) {
$s = @fread($fp, 8192);
if (
$s === false)
break;
//тут бесполезно отправлять сообщения об ошибках

echo $s;
}
?>

Этот пример открывает RAR-файл и предоставляет запрошенный файл вне RAR-архива для загрузки клиентом.

Пример #2 Пример извлечения перечня файлов и директорий из RAR-архива

<?php

$rar_file
= rar_open('example.rar') or die("Невозможно открыть RAR архив");

$entries = rar_list($rar_file);

foreach (
$entries as $entry) {
echo
'Имя файла: ' . $entry->getName() . "\n";
echo
'Упакованный размер: ' . $entry->getPackedSize() . "\n";
echo
'Распакованный размер: ' . $entry->getUnpackedSize() . "\n";

$entry->extract('/dir/extract/to/');
}

rar_close($rar_file);

?>

Этот пример открывает RAR-файл и извлекает каждый объект в указанную директорию.

add a note

User Contributed Notes 1 note

up
1
Nitrogen
13 years ago
A veeery simple function to RAR files, I'm not proud of it.
Since there's no way to create RAR files in PHP (due to licensing, patents or whatever), I'm taking some advantage from the command-line RARing tool that comes with WinRAR (in the WinRAR program files named "rar.exe").

<?php
function RARFiles($Output='output.rar',$Files=array()) {
$Data='';
for(
$i=0;$i<count($Files);$i++)
$Data.="\"{$Files[$i]}\" ";
exec("rar.exe a \"{$Output}\" {$Data}");
}

$Files=array('file1.ext','file2.ext','file3.ext');
RARFiles('asdf.rar',$Files);
// asdf.rar created.
?>

There's no error checking, so make sure you check that your expected RAR file exists before doing anything with it.
Hopefully one day, PHP will be able to be allowed to create RAR files.
To Top