-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathexamples.xml
More file actions
176 lines (143 loc) · 5.52 KB
/
Copy pathexamples.xml
File metadata and controls
176 lines (143 loc) · 5.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
<?xml version="1.0" encoding="utf-8"?>
<!-- EN-Revision: ee741f54f831af19f135d1d9894a41477ab896c3 Maintainer: shein Status: ready -->
<!-- Reviewed: no -->
<chapter xmlns="http://docbook.org/ns/docbook" xmlns:xlink="http://www.w3.org/1999/xlink" xml:id="rar.examples">
&reftitle.examples;
<simpara>
Смотрите также примеры по ссылке <link linkend="wrappers.rar">обёртка <literal>rar://</literal></link>.
</simpara>
<example>
<title>Декомпрессия на лету</title>
<programlisting role="php">
<![CDATA[
<?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));
// Невозможна дальнейшая отправка сообщений об ошибках (PHP уже отправил заголовки)
// Замена на реальный 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;
}
?>
]]>
</programlisting>
</example>
<simpara>
Этот пример открывает RAR-файл и предоставляет запрошенный файл вне RAR-архива для загрузки клиентом.
</simpara>
<example>
<title>Пример извлечения перечня файлов и директорий из RAR-архива</title>
<programlisting role="php">
<![CDATA[
<?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);
?>
]]>
</programlisting>
</example>
<simpara>
Этот пример открывает RAR-файл и извлекает каждый объект
в заданную директорию.
</simpara>
</chapter>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:1
sgml-indent-data:t
indent-tabs-mode:nil
sgml-parent-document:nil
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
vim600: syn=xml fen fdm=syntax fdl=2 si
vim: et tw=78 syn=sgml
vi: ts=1 sw=1
-->