PHP: полный мануал с примерами, функциями и ООП
Практический мануал PHP: от переменных и читаемого кода до безопасных форм, интеграций, базы данных и ООП на примере магазина. Учебный маршрут, поиск функций, подробные примеры, разбор ошибок и исходники для скачивания.

Дерево руководства
Глава 466 · Официальная база → практическое применение
Потоковые фильтры и транспорты сокетов
От строкового преобразования до TCP/TLS и Unix sockets: что меняется на пути байтов и где обрабатывать отказ.
Доступные потоковые фильтры
Потоковый фильтр преобразует проходящие байты при чтении или записи. Порядок фильтров меняет результат; доступность зависит от расширений. Для архива, шифрования и текста заранее фиксируют формат, кодировку и ошибку недоступного фильтра.
Полный официальный договор страницы
Ниже сохранён официальный русский текст и структура из зафиксированного архива PHP Manual. Отдельные ещё не переведённые страницы официального русского архива могут оставаться на английском.
Раздел описывает ряд встроенных фильтров, которые функцией stream_filter_append() добавляют в цепочку обработки потока данных. На количество доступных фильтров влияют конкретная версия и сборка PHP.
Функции stream_filter_append() и stream_filter_prepend() работают асимметрично. Каждый поток данных в PHP содержит буфер чтения. В буфере хранятся блоки данных, которые поток получил из файловой системы или другого источника. Буферизация оптимизирует операции ввода и вывода при обработке данных. Сразу после извлечения из ресурса данные обрабатываются фильтрами, которые добавили в цепочку обработки потока данных, и записываются во внутренний буфер потока, независимо от готовности PHP-приложения принимать данные. Данные в буфере чтения немедленно обрабатываются новым фильтром при добавлении фильтра в конец цепочки, хотя данные и содержались в буфере на момент добавления фильтра. При этом данные буфера чтения НЕ обрабатываются фильтром, который добавляют в начало цепочки. Такой фильтр ожидает считывания из источника нового блока данных.
Список установленных в конкретной версии PHP фильтров возвращает функция stream_get_filters().
Нормативный английский оригинал из frozen baseline
Этот слой сохраняет полный договор, если перевод отстаёт. Источник: английский нормативный оригинал.
The following is a list of a few built-in stream filters for use with stream_filter_append(). Your version of PHP may have more filters (or fewer) than those listed here.
It is worth noting a slight asymmetry between stream_filter_append() and stream_filter_prepend(). Every PHP stream contains a small read buffer where it stores blocks of data retrieved from the filesystem or other resource in order to process data in the most efficient manner. As soon as data is pulled from the resource into the stream's internal buffer, it is immediately processed through any attached filters whether the PHP application is actually ready for the data or not. If data is sitting in the read buffer when a filter is appended, this data will be immediately processed through that filter making the fact that it was sitting in the buffer seem transparent. However, if data is sitting in the read buffer when a filter is prepended, this data will NOT be processed through that filter. It will instead wait until the next block of data is retrieved from the resource.
For a list of filters installed in your version of PHP use stream_get_filters().
Фильтры сжатия
Потоковый фильтр преобразует проходящие байты при чтении или записи. Порядок фильтров меняет результат; доступность зависит от расширений. Для архива, шифрования и текста заранее фиксируют формат, кодировку и ошибку недоступного фильтра.
Полный официальный договор страницы
Ниже сохранён официальный русский текст и структура из зафиксированного архива PHP Manual. Отдельные ещё не переведённые страницы официального русского архива могут оставаться на английском.
Хотя обёртки сжатия и создают gzip- и bz2-совместимые файлы в локальной файловой системе, они не предоставляют общих средств для компрессии в сетевых потоках, как и не предоставляют средств для создания потока без компрессии с последующим превращением в компрессируемый. Для этих целей к любым потоковым ресурсам в любое время применяют фильтры сжатия.
Замечание:
Фильтры сжатия не генерируют заголовочных и хвостовых блоков архива, которые создают утилиты командной строки наподобие
gzip. Фильтры сжатия только сжимают и распаковывают порции данных в компрессируемом потоке данных.
zlib.deflate и zlib.inflate
zlib.deflate (компрессия)
и zlib.inflate (декомпрессия) являются реализациями
методов сжатия, описанных в
» RFC 1951.
Фильтр deflate принимает три аргумента, переданных
в виде ассоциативного массива.
level определяет, какой уровень компрессии
использовать (1-9). Повышение этого значения приведёт к уменьшению
объёмов данных за счёт увеличения времени обработки. Существуют также два
специальных уровня компрессии:
0 (для отключения компрессии) и -1 (внутреннее значение по умолчанию
библиотеки zlib -- на текущий момент равно 6).
window - это логарифм с основанием 2 от размера окна диапазона сжатия.
Высокие значения (вплоть до 15 -- 32768 байт) приводят к улучшению
компрессии за счёт роста необходимой памяти, в то время как низкие значения
(вплоть до 9 -- 512 байт) приводят к ухудшению компрессии за счёт
уменьшения необходимой памяти.
Значением аргумента window по умолчанию на текущий
момент является 15.
memory определяет масштаб резервируемой памяти.
Допустимые значения находятся в диапазоне от 1 (минимальное резервирование)
до 9 (максимальное резервирование). Такое резервирование памяти влияет
только на скорость и не влияет на размер генерируемых данных.
Замечание:
Так как уровень компрессии является наиболее часто используемым аргументом, вы можете передать только его в качестве обычного целого числа (integer), вместо того чтобы передавать массив из одного элемента.
Компрессионные фильтры zlib.* доступны, если включена поддержка zlib.
Пример #1
zlib.deflate
и zlib.inflate
<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "Оригинальный текст длиной " . strlen($original_text) . " символов.\n";
$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);
echo "Сжатый файл размером " . filesize('test.deflated') . " байт.\n";
echo "Оригинальный текст:\n";
/* Использование readfile и zlib.inflate для декомпресии на лету */
readfile('php://filter/zlib.inflate/resource=test.deflated');
/* Генерирует вывод:
Оригинальный текст длиной 70 символов.
Сжатый файл размером 56 байт.
Оригинальный текст:
This is a test.
This is only a test.
This is not an important string.
*/Пример #2
Упрощённая работа фильтра zlib.deflate
<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "Оригинальный текст длиной " . strlen($original_text) . " символов.\n";
$fp = fopen('test.deflated', 'w');
/* Здесь аргумент 6 указывает уровень компрессии 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);
echo "Сжатый файл размером " . filesize('test.deflated') . " байт.\n";
/* Генерирует вывод:
Оригинальный текст длиной 70 символов.
Сжатый файл размером 56 байт.
*/bzip2.compress и bzip2.decompress
Фильтры bzip2.compress
и bzip2.decompress
работают аналогично zlib-фильтрам, которые уже описывались.
Фильтр bzip2.compress принимает два аргумента в виде
элементов ассоциативного массива:
blocks является целочисленным (integer) значением
в диапазоне от 1 до 9 и указывает на количество 100-килобайтных блоков
памяти для резервирования в качестве рабочего пространства.
work - это так же целочисленное (integer) значение
в диапазоне от 0 до 250, определяющее сколько усилий нужно потратить на
обычный метод компрессии перед переключением на медленный, но более
надёжный метод. Изменение этого параметра влияет только на скорость
компрессии. Ни размер сжатого результата, ни используемый объем памяти не
изменяются при помощи этой настройки. Значение 0 указывает библиотеке bzip
использовать собственное внутреннее значение по умолчанию.
Фильтр bzip2.decompress принимает всего один аргумент,
который может быть передан либо как обычное boolean-значение, либо как
элемент small ассоциативного массива.
Когда small установлен в true, библиотека bzip
совершит декомпрессию с минимальным расходом памяти за счёт понижения
скорости.
Компрессионные фильтры bzip2.* доступны, если включена поддержка bz2.
Пример #3
bzip2.compress
и bzip2.decompress
<?php
$param = array('blocks' => 9, 'work' => 0);
echo "Оригинальный файл размером " . filesize('LICENSE') . " байт.\n";
$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);
echo "Сжатый файл размером " . filesize('LICENSE.compressed') . " байт.\n";
/* Генерирует вывод:
Оригинальный файл размером 3288 байт.
Сжатый файл размером 1488 байт.
*/Нормативный английский оригинал из frozen baseline
Этот слой сохраняет полный договор, если перевод отстаёт. Источник: английский нормативный оригинал.
While the Compression Wrappers provide a way of creating gzip and bz2 compatible files on the local filesystem, they do not provide a means for generalized compression over network streams, nor do they provide a means to begin with a non-compressed stream and transition to a compressed one. For this, a compression filter may be applied to any stream resource at any time.
Note:
Compression filters do not generate headers and trailers used by command line utilities such as
gzip. They only compress and decompress the payload portions of compressed data streams.
zlib.deflate and zlib.inflate
zlib.deflate (compression) and
zlib.inflate (decompression) are implementations of
the compression methods described in » RFC 1951.
The deflate filter takes up to three parameters passed as
an associative array.
level describes the compression
strength to use (1-9). Higher numbers will generally yield smaller payloads at
the cost of additional processing time. Two special compression levels also exist:
0 (for no compression at all), and -1 (zlib internal default -- currently 6).
window is the base-2 log of the compression loopback window size.
Higher values (up to 15 -- 32768 bytes) yield better compression at a cost of memory,
while lower values (down to 9 -- 512 bytes) yield worse compression in a smaller memory footprint.
Default window size is currently 15.
The zlib.deflate filter implements the compression
methods DEFLATE, ZLIB and
GZIP depending on the value of the
window parameter.
The 4 lower bits of the window parameter set the size of the internal
“history buffer” used, being the base-2 logarithm of its size in a range
from 8 up to 15. The meaning of the others bits of the window parameter
can be set as described below.
DEFLATE(» RFC 1951) is a raw compression algorithm without header, without checksum. It is performed when the window parameter is set in the range from -9 up to -15. This compression algorithm is the base for all the formats generated by thezlib.deflatefilter. The corresponding functions that operate directly on strings are gzdeflate() and gzinflate().ZLIB(» RFC 1950) applies theDEFLATEalgorithm and adds a 2 bytes header and 4 bytes trailer containing the Adler32 checksum of the uncompressed data in big-endian byte order:The 2 bytes header, read as 16 bit unsigned number in big-endian order, must be multiple of 31. This format is generated when the window parameter is set in the range from 8 up to 15. The corresponding functions that operate directly on strings are gzcompress() and gzuncompress().ZLIB = ZLIBHEADER(2B) DEFLATE ADLER32(4B)
GZIP(» RFC 1952) applies theDEFLATEalgorithm adding an header and a trailer with theCRC32checksum of the uncompressed data and their length, both in little-endian byte ordering:This is the format of theGZIP = GZIPHEADER(10B) DEFLATE CRC32(4B) LENGTH(4B)
.gzfiles, with theGZIPHEADERcontaining in the order theGZIPsignature (\x1f\x8B), the compression method (\x08), a zero flag byte, a zero modification time on 4 bytes, an extra-flags byte that depends on the compression level, and the operating system set to the current system (\x00= FAT filesystem,\x03= Unix, etc.). This format is generated when the window parameter is set in the range from 9+16=25 up to 15+16=31. Note that there is a limit of 4GB to the maximum length of the uncompressed data; beyond this limit, only the modulo 2^32 of the actual length is stored in theLENGTHpart. The corresponding functions that operate directly on strings are gzencode() and gzdecode(); the gzopen() function allows to read and write.gzfiles.
zlib.inflate filter, only the
window parameter is allowed; any other parameter
(memory, level) is ignored.
Be $W the base-2 log of the history buffer size, so that 2^$W bytes are
allocated by the decompressor. For the ZLIB format this value must be
greater or equal to the one recorded in the header, which is checked at
decompression time; for the other formats it only has to be large enough
for the match distances actually present in the data.
The range is 9 ≤ $W ≤ 15. If unknown, $W=15 is the safer choice.
DEFLATE(» RFC 1951): use window=-$W, with $W being a value not less than that used for compression. If unknown, set window=-15.ZLIB(» RFC 1950): use window=$W. The value of $W is available from the same ZLIB header, otherwise set window=15.GZIP(» RFC 1952): use window=$W+16. A GZIP header carries no window size, so set window=31 unless the value used for compression is known.ZLIB or GZIP: use window=$W+32 for automatic header detection, so that both the formats can be recognized and decompressed; window=15+32=47 is the safer choice.
memory is a scale indicating how much work memory should be allocated.
Valid values range from 1 (minimal allocation) to 9 (maximum allocation). This memory allocation
affects speed only and does not impact the size of the generated payload.
Note:
Because compression level is the most commonly used parameter, it may be alternatively provided as a simple integer value (rather than an array element).
zlib.* compression filters are available if zlib support is enabled.
Example #1
zlib.deflate and
zlib.inflate
<?php
$params = array('level' => 6, 'window' => 15, 'memory' => 9);
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";
$fp = fopen('test.deflated', 'w');
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, $params);
fwrite($fp, $original_text);
fclose($fp);
echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";
echo "The original text was:\n";
/* Use readfile and zlib.inflate to decompress on the fly */
readfile('php://filter/zlib.inflate/resource=test.deflated');
/* Generates output:
The original text is 70 characters long.
The compressed file is 56 bytes long.
The original text was:
This is a test.
This is only a test.
This is not an important string.
*/
?>Example #2
zlib.deflate simple
<?php
$original_text = "This is a test.\nThis is only a test.\nThis is not an important string.\n";
echo "The original text is " . strlen($original_text) . " characters long.\n";
$fp = fopen('test.deflated', 'w');
/* Here "6" indicates compression level 6 */
stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_WRITE, 6);
fwrite($fp, $original_text);
fclose($fp);
echo "The compressed file is " . filesize('test.deflated') . " bytes long.\n";
/* Generates output:
The original text is 70 characters long.
The compressed file is 56 bytes long.
*/
?>bzip2.compress and bzip2.decompress
bzip2.compress and
bzip2.decompress
work in the same manner as the zlib filters described above.
The bzip2.compress filter accepts up to two parameters given as
elements of an associative array:
blocks is an integer value
from 1 to 9 specifying the number of 100kbyte blocks of memory to allocate for
workspace.
work is also an integer value ranging from
0 to 250 indicating how much effort to expend using the normal compression method
before falling back on a slower, but more reliable method. Tuning this parameter
effects only compression speed. Neither size of compressed output nor memory usage
are changed by this setting. A work factor of 0 instructs the bzip library to use
an internal default.
The bzip2.decompress filter only accepts one parameter,
which can be passed as either an ordinary boolean value, or as the
small element of an associative array.
small, when set to a true value, instructs the bzip library
to perform decompression in a minimal memory footprint at the cost of speed.
bzip2.* compression filters are available if bz2 support is enabled.
Example #3
bzip2.compress and
bzip2.decompress
<?php
$param = array('blocks' => 9, 'work' => 0);
echo "The original file is " . filesize('LICENSE') . " bytes long.\n";
$fp = fopen('LICENSE.compressed', 'w');
stream_filter_append($fp, 'bzip2.compress', STREAM_FILTER_WRITE, $param);
fwrite($fp, file_get_contents('LICENSE'));
fclose($fp);
echo "The compressed file is " . filesize('LICENSE.compressed') . " bytes long.\n";
/* Generates output:
The original file is 3288 bytes long.
The compressed file is 1488 bytes long.
*/
?>Фильтры преобразования
Потоковый фильтр преобразует проходящие байты при чтении или записи. Порядок фильтров меняет результат; доступность зависит от расширений. Для архива, шифрования и текста заранее фиксируют формат, кодировку и ошибку недоступного фильтра.
Полный официальный договор страницы
Ниже сохранён официальный русский текст и структура из зафиксированного архива PHP Manual. Отдельные ещё не переведённые страницы официального русского архива могут оставаться на английском.
Как и фильтры string.*, фильтры convert.* совершают действия, соответствующие их именам. Для получения дополнительной информации о конкретном фильтре, обратитесь к странице руководства соответствующей функции.
convert.base64-encode и convert.base64-decode
Работа фильтров эквивалентна обработке всех данных потока
функциями base64_encode()
и base64_decode() соответственно.
Фильтр convert.base64-encode поддерживает аргументы,
которые передали как ассоциативный массив. С аргументом
line-length результат base64 разделится
на куски длинной line-length символов каждый.
С аргументом line-break-chars
каждый кусок разделяется заданными символами. Эффект этих параметров
аналогичен работе функции base64_encode()
в паре с функцией chunk_split().
Пример #1 Пример работы фильтров convert.base64-encode и convert.base64-decode
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Выведет: VGhpcyBpcyBhIHRlc3QuCg== */
$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Выведет: VGhpcyBp
: cyBhIHRl
: c3QuCg== */
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Выведет: This is a test. */convert.quoted-printable-encode и convert.quoted-printable-decode
Работа decode-версии этого фильтра эквивалентна обработке всех
данных потока функцией quoted_printable_decode().
У фильтра convert.quoted-printable-encode нет
эквивалентной функции.
Фильтр convert.quoted-printable-encode поддерживает аргументы,
которые передали как ассоциативный массив. В дополнение к аргументам,
которые поддерживает фильтр convert.base64-encode,
фильтр convert.quoted-printable-encode также поддерживает
boolean-аргументы binary
и force-encode-first.
Фильтр convert.base64-decode поддерживает только аргумент
line-break-chars как подсказку
для чистки закодированных данных.
Пример #2 Пример работы фильтров convert.quoted-printable-encode & convert.quoted-printable-decode
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Выведет: =This is a test.=0A */convert.iconv.*
Фильтры convert.iconv.* доступны в том случае, если
включена поддержка iconv и их использование
аналогично обработке потоковых данных с помощью iconv().
Эти фильтры не поддерживают параметров. Вместо этого ожидается, что
исходная и целевая кодировки были заданы в имени фильтра таким образом:
convert.iconv.<input-encoding>.<output-encoding>
или convert.iconv.<input-encoding>/<output-encoding>
(оба варианта семантически эквивалентны).
Пример #3 convert.iconv.*
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.iconv.utf-16le.utf-8');
fwrite($fp, "T\0h\0i\0s\0 \0i\0s\0 \0a\0 \0t\0e\0s\0t\0.\0\n\0");
fclose($fp);
/* Выведет: This is a test. */Нормативный английский оригинал из frozen baseline
Этот слой сохраняет полный договор, если перевод отстаёт. Источник: английский нормативный оригинал.
Like the string.* filters, the convert.* filters perform actions similar to their names. For more information on a given filter, refer to the manual page for the corresponding function.
convert.base64-encode and convert.base64-decode
Use of these filters are equivalent to processing all stream data through
the base64_encode() and base64_decode()
functions respectively.
convert.base64-encode supports parameters given as
an associative array. If line-length is given, the
base64 output will be split into chunks of line-length
characters each. If line-break-chars is given, each
chunk will be delimited by the characters given. These parameters give the
same effect as using base64_encode() with
chunk_split().
Example #1 convert.base64-encode & convert.base64-decode
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode');
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs: VGhpcyBpcyBhIHRlc3QuCg== */
$param = array('line-length' => 8, 'line-break-chars' => "\r\n");
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-encode', STREAM_FILTER_WRITE, $param);
fwrite($fp, "This is a test.\n");
fclose($fp);
/* Outputs: VGhpcyBp
: cyBhIHRl
: c3QuCg== */
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.base64-decode');
fwrite($fp, "VGhpcyBpcyBhIHRlc3QuCg==");
fclose($fp);
/* Outputs: This is a test. */
?>convert.quoted-printable-encode and convert.quoted-printable-decode
Use of the decode version of this filter is equivalent to processing all stream
data through the quoted_printable_decode() function.
There is no function equivalent to convert.quoted-printable-encode.
convert.quoted-printable-encode supports parameters given as
an associative array. In addition to the parameters supported by
convert.base64-encode, convert.quoted-printable-encode
also supports boolean arguments binary and
force-encode-first.
convert.base64-decode only supports the
line-break-chars parameter as a type-hint
for stripping from the encoded payload.
Example #2 convert.quoted-printable-encode & convert.quoted-printable-decode
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.quoted-printable-encode');
fwrite($fp, "This is a test.\n");
/* Outputs: =This is a test.=0A */
?>convert.iconv.*
The convert.iconv.* filters are available, if
iconv support is enabled, and their use is
equivalent to processing all stream data with iconv().
These filters do not support parameters, but instead expect the input and
output encodings to be given as part of the filter name, i.e. either as
convert.iconv.<input-encoding>.<output-encoding> or
convert.iconv.<input-encoding>/<output-encoding>
(both notations are semantically equivalent).
Example #3 convert.iconv.*
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'convert.iconv.utf-16le.utf-8');
fwrite($fp, "T\0h\0i\0s\0 \0i\0s\0 \0a\0 \0t\0e\0s\0t\0.\0\n\0");
fclose($fp);
/* Outputs: This is a test. */
?>Фильтры шифрования
Потоковый фильтр преобразует проходящие байты при чтении или записи. Порядок фильтров меняет результат; доступность зависит от расширений. Для архива, шифрования и текста заранее фиксируют формат, кодировку и ошибку недоступного фильтра.
Полный официальный договор страницы
Ниже сохранён официальный русский текст и структура из зафиксированного архива PHP Manual. Отдельные ещё не переведённые страницы официального русского архива могут оставаться на английском.
Шифрующие фильтры очень хорошо подходят для шифрования файлов и потоков.
mcrypt.* и mdecrypt.*
Начиная с PHP 7.1.0 функция УСТАРЕЛА. Полагаться на функцию настоятельно не рекомендуют.
mcrypt.* и mdecrypt.*
обеспечивают симметричное шифрование и дешифровку через библиотеку
libmcrypt. Оба набора фильтров поддерживают те же алгоритмы,
что и модуль mcrypt в виде
фильтра mcrypt.ciphername,
где ciphername — название шифра, как если
бы оно передавалось функции mcrypt_module_open().
Также доступны следующие пять параметров:
| Параметр | Обязателен? | По умолчанию | Пример значения |
|---|---|---|---|
| mode | Нет | cbc | cbc, cfb, ecb, nofb, ofb, stream |
| algorithms_dir | Нет | ini_get('mcrypt.algorithms_dir') | Путь к модулям алгоритмов |
| modes_dir | Нет | ini_get('mcrypt.modes_dir') | Путь к модулям режимов |
| iv | Да | N/A | Обычно 8, 16 или 32 байта бинарных данных. Зависит от шифра |
| key | Да | N/A | Обычно 8, 16 или 32 байта бинарных данных. Зависит от шифра |
Пример #1 Шифрование алгоритмом Blowfish и расшифровка
<?php
// Примем, что ключ $key уже сформировали
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$fp = fopen('encrypted-file.enc', 'wb');
fwrite($fp, $iv);
$opts = array('mode' => 'cbc', 'iv' => $iv, 'key' => $key);
stream_filter_append($fp, 'mcrypt.blowfish', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'message to encrypt');
fclose($fp);
// Расшифровка...
$fp = fopen('encrypted-file.enc', 'rb');
$iv = fread($fp, $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC));
$opts = array('mode' => 'cbc', 'iv' => $iv, 'key' => $key);
stream_filter_append($fp, 'mdecrypt.blowfish', STREAM_FILTER_READ, $opts);
$data = rtrim(stream_get_contents($fp)); //trims off null padding
fclose($fp);
echo $data;Пример #2 Шифрование файла алгоритмом SHA256 HMAC в режиме AES-128 CBC
<?php
AES_CBC::encryptFile($password, "plaintext.txt", "encrypted.enc");
AES_CBC::decryptFile($password, "encrypted.enc", "decrypted.txt");
class AES_CBC
{
protected static $KEY_SIZES = array('AES-128' => 16, 'AES-192' => 24, 'AES-256' => 32);
protected static function key_size()
{
return self::$KEY_SIZES['AES-128'];
} // default AES-128
public static function encryptFile($password, $input_stream, $aes_filename)
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$fin = fopen($input_stream, "rb");
$fc = fopen($aes_filename, "wb+");
if (!empty($fin) && !empty($fc)) {
fwrite($fc, str_repeat("_", 32)); //placeholder, SHA256 HMAC will go here later
fwrite($fc, $hmac_salt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
fwrite($fc, $esalt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
fwrite($fc, $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it = 1000, self::key_size(), $raw = true);
$opts = array('mode' => 'cbc', 'iv' => $iv, 'key' => $ekey);
stream_filter_append($fc, 'mcrypt.rijndael-128', STREAM_FILTER_WRITE, $opts);
$infilesize = 0;
while (!feof($fin)) {
$block = fread($fin, 8192);
$infilesize += strlen($block);
fwrite($fc, $block);
}
$block_size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $block_size - ($infilesize % $block_size); //$padding is a number from 1-16
fwrite($fc, str_repeat(chr($padding), $padding)); //perform PKCS7 padding
fclose($fin);
fclose($fc);
$hmac_raw = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb+");
fwrite($fc, $hmac_raw); //overwrite placeholder
fclose($fc);
}
}
public static function decryptFile($password, $aes_filename, $out_stream)
{
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$hmac_raw = file_get_contents($aes_filename, false, NULL, 0, 32);
$hmac_salt = file_get_contents($aes_filename, false, NULL, 32, $iv_size);
$hmac_calc = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb");
$fout = fopen($out_stream, 'wb');
if (!empty($fout) && !empty($fc) && self::hash_equals($hmac_raw, $hmac_calc)) {
fread($fc, 32 + $iv_size); //skip sha256 hmac and salt
$esalt = fread($fc, $iv_size);
$iv = fread($fc, $iv_size);
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it = 1000, self::key_size(), $raw = true);
$opts = array('mode' => 'cbc', 'iv' => $iv, 'key' => $ekey);
stream_filter_append($fc, 'mdecrypt.rijndael-128', STREAM_FILTER_READ, $opts);
while (!feof($fc)) {
$block = fread($fc, 8192);
if (feof($fc)) {
$padding = ord($block[strlen($block) - 1]); //assume PKCS7 padding
$block = substr($block, 0, 0 - $padding);
}
fwrite($fout, $block);
}
fclose($fout);
fclose($fc);
}
}
private static function hash_equals($str1, $str2)
{
if (strlen($str1) == strlen($str2)) {
$res = $str1 ^ $str2;
for ($ret = 0, $i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
return !$ret;
}
return false;
}
private static function calculate_hmac_after_32bytes($password, $hsalt, $filename)
{
static $init = 0;
$init or $init = stream_filter_register("user-filter.skipfirst32bytes", "FileSkip32Bytes");
$stream = 'php://filter/read=user-filter.skipfirst32bytes/resource=' . $filename;
$hkey = hash_pbkdf2("sha256", $password, $hsalt, $iterations = 1000, 24, $raw = true);
return hash_hmac_file('sha256', $stream, $hkey, $raw = true);
}
}
class FileSkip32Bytes extends php_user_filter
{
private $skipped = 0;
function filter($in, $out, &$consumed, $closing)
{
while ($bucket = stream_bucket_make_writeable($in)) {
$outlen = $bucket->datalen;
if ($this->skipped < 32) {
$outlen = min($bucket->datalen, 32 - $this->skipped);
$bucket->data = substr($bucket->data, $outlen);
$bucket->datalen = $bucket->datalen - $outlen;
$this->skipped += $outlen;
}
$consumed += $outlen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
class AES_128_CBC extends AES_CBC
{
protected static function key_size()
{
return self::$KEY_SIZES['AES-128'];
}
}
class AES_192_CBC extends AES_CBC
{
protected static function key_size()
{
return self::$KEY_SIZES['AES-192'];
}
}
class AES_256_CBC extends AES_CBC
{
protected static function key_size()
{
return self::$KEY_SIZES['AES-256'];
}
}Нормативный английский оригинал из frozen baseline
Этот слой сохраняет полный договор, если перевод отстаёт. Источник: английский нормативный оригинал.
Encryption filters are especially useful for file/stream encryption.
mcrypt.* and mdecrypt.*
This feature has been DEPRECATED as of PHP 7.1.0. Relying on this feature is highly discouraged.
mcrypt.* and mdecrypt.*
provide symmetric encryption and decryption using libmcrypt.
Both sets of filters support the same algorithms available to
mcrypt extension in the form of
mcrypt.ciphername where ciphername
is the name of the cipher as it would be passed to
mcrypt_module_open().
The following five filter parameters are also available:
| Parameter | Required? | Default | Sample Values |
|---|---|---|---|
| mode | Optional | cbc | cbc, cfb, ecb, nofb, ofb, stream |
| algorithms_dir | Optional | ini_get('mcrypt.algorithms_dir') | Location of algorithms modules |
| modes_dir | Optional | ini_get('mcrypt.modes_dir') | Location of modes modules |
| iv | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher |
| key | Required | N/A | Typically 8, 16, or 32 bytes of binary data. Depends on cipher |
Example #1 Encrypt/Decrypt with Blowfish
<?php
//$key assumed to be previously generated
$iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM);
$fp = fopen('encrypted-file.enc', 'wb');
fwrite($fp, $iv);
$opts = array('mode'=>'cbc','iv'=>$iv, 'key'=>$key);
stream_filter_append($fp, 'mcrypt.blowfish', STREAM_FILTER_WRITE, $opts);
fwrite($fp, 'message to encrypt');
fclose($fp);
//decrypt...
$fp = fopen('encrypted-file.enc', 'rb');
$iv = fread($fp, $iv_size = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC));
$opts = array('mode'=>'cbc','iv'=>$iv, 'key'=>$key);
stream_filter_append($fp, 'mdecrypt.blowfish', STREAM_FILTER_READ, $opts);
$data = rtrim(stream_get_contents($fp));//trims off null padding
fclose($fp);
echo $data;
?>Example #2 Encrypt file using AES-128 CBC with SHA256 HMAC
<?php
AES_CBC::encryptFile($password, "plaintext.txt", "encrypted.enc");
AES_CBC::decryptFile($password, "encrypted.enc", "decrypted.txt");
class AES_CBC
{
protected static $KEY_SIZES = array('AES-128'=>16,'AES-192'=>24,'AES-256'=>32);
protected static function key_size() { return self::$KEY_SIZES['AES-128']; } //default AES-128
public static function encryptFile($password, $input_stream, $aes_filename){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$fin = fopen($input_stream, "rb");
$fc = fopen($aes_filename, "wb+");
if (!empty($fin) && !empty($fc)) {
fwrite($fc, str_repeat("_", 32) );//placeholder, SHA256 HMAC will go here later
fwrite($fc, $hmac_salt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
fwrite($fc, $esalt = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
fwrite($fc, $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM));
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
$opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
stream_filter_append($fc, 'mcrypt.rijndael-128', STREAM_FILTER_WRITE, $opts);
$infilesize = 0;
while (!feof($fin)) {
$block = fread($fin, 8192);
$infilesize+=strlen($block);
fwrite($fc, $block);
}
$block_size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$padding = $block_size - ($infilesize % $block_size);//$padding is a number from 1-16
fwrite($fc, str_repeat(chr($padding), $padding) );//perform PKCS7 padding
fclose($fin);
fclose($fc);
$hmac_raw = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb+");
fwrite($fc, $hmac_raw);//overwrite placeholder
fclose($fc);
}
}
public static function decryptFile($password, $aes_filename, $out_stream) {
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$hmac_raw = file_get_contents($aes_filename, false, NULL, 0, 32);
$hmac_salt = file_get_contents($aes_filename, false, NULL, 32, $iv_size);
$hmac_calc = self::calculate_hmac_after_32bytes($password, $hmac_salt, $aes_filename);
$fc = fopen($aes_filename, "rb");
$fout = fopen($out_stream, 'wb');
if (!empty($fout) && !empty($fc) && self::hash_equals($hmac_raw,$hmac_calc)) {
fread($fc, 32+$iv_size);//skip sha256 hmac and salt
$esalt = fread($fc, $iv_size);
$iv = fread($fc, $iv_size);
$ekey = hash_pbkdf2("sha256", $password, $esalt, $it=1000, self::key_size(), $raw=true);
$opts = array('mode'=>'cbc', 'iv'=>$iv, 'key'=>$ekey);
stream_filter_append($fc, 'mdecrypt.rijndael-128', STREAM_FILTER_READ, $opts);
while (!feof($fc)) {
$block = fread($fc, 8192);
if (feof($fc)) {
$padding = ord($block[strlen($block) - 1]);//assume PKCS7 padding
$block = substr($block, 0, 0-$padding);
}
fwrite($fout, $block);
}
fclose($fout);
fclose($fc);
}
}
private static function hash_equals($str1, $str2) {
if(strlen($str1) == strlen($str2)) {
$res = $str1 ^ $str2;
for($ret=0,$i = strlen($res) - 1; $i >= 0; $i--) $ret |= ord($res[$i]);
return !$ret;
}
return false;
}
private static function calculate_hmac_after_32bytes($password, $hsalt, $filename) {
static $init=0;
$init or $init = stream_filter_register("user-filter.skipfirst32bytes", "FileSkip32Bytes");
$stream = 'php://filter/read=user-filter.skipfirst32bytes/resource=' . $filename;
$hkey = hash_pbkdf2("sha256", $password, $hsalt, $iterations=1000, 24, $raw=true);
return hash_hmac_file('sha256', $stream, $hkey, $raw=true);
}
}
class FileSkip32Bytes extends php_user_filter
{
private $skipped=0;
function filter($in, $out, &$consumed, $closing) {
while ($bucket = stream_bucket_make_writeable($in)) {
$outlen = $bucket->datalen;
if ($this->skipped<32){
$outlen = min($bucket->datalen,32-$this->skipped);
$bucket->data = substr($bucket->data, $outlen);
$bucket->datalen = $bucket->datalen-$outlen;
$this->skipped+=$outlen;
}
$consumed += $outlen;
stream_bucket_append($out, $bucket);
}
return PSFS_PASS_ON;
}
}
class AES_128_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-128']; }
}
class AES_192_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-192']; }
}
class AES_256_CBC extends AES_CBC {
protected static function key_size() { return self::$KEY_SIZES['AES-256']; }
}Строковые фильтры
Потоковый фильтр преобразует проходящие байты при чтении или записи. Порядок фильтров меняет результат; доступность зависит от расширений. Для архива, шифрования и текста заранее фиксируют формат, кодировку и ошибку недоступного фильтра.
Полный официальный договор страницы
Ниже сохранён официальный русский текст и структура из зафиксированного архива PHP Manual. Отдельные ещё не переведённые страницы официального русского архива могут оставаться на английском.
Каждый фильтр выполняет подразумеваемую названием работу, которая соответствует поведению встроенных в PHP функций для работы со строками. Страницы руководства с описанием функций дают дополнительную информацию о конкретном фильтре.
string.rot13
Работа фильтра эквивалентна обработке всех данных потока функцией str_rot13().
Пример #1 string.rot13
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Выведет: Guvf vf n grfg. */string.toupper
Работа фильтра эквивалентна обработке всех данных потока функцией strtoupper().
Пример #2 string.toupper
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Выведет: THIS IS A TEST. */string.tolower
Работа фильтра эквивалентна обработке всех данных потока функцией strtolower().
Пример #3 string.tolower
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Выведет: this is a test. */string.strip_tags
Работа фильтра эквивалентна обработке всех данных потока функцией strip_tags(). Фильтр принимает аргументы в одной из двух форм: либо в виде строки со списком тегов, как и второй аргумент функции strip_tags(), либо массив названий тегов.
Начиная с PHP 7.3.0 функциональность УСТАРЕЛА. Полагаться на функциональность настоятельно не рекомендуют.
Пример #4 string.strip_tags
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<b><i><u>");
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Выведет: bolded text enlarged to a level 1 heading */
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b', 'i', 'u'));
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Выведет: bolded text enlarged to a level 1 heading */Нормативный английский оригинал из frozen baseline
Этот слой сохраняет полный договор, если перевод отстаёт. Источник: английский нормативный оригинал.
Each of these filters does precisely what their name implies and correspond to the behavior of a built-in php string handling function. For more information on a given filter, refer to the manual page for the corresponding function.
string.rot13
Use of this filter is equivalent to processing all stream data through the str_rot13() function.
Example #1 string.rot13
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.rot13');
fwrite($fp, "This is a test.\n");
/* Outputs: Guvf vf n grfg. */
?>string.toupper
Use of this filter is equivalent to processing all stream data through the strtoupper() function.
Example #2 string.toupper
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.toupper');
fwrite($fp, "This is a test.\n");
/* Outputs: THIS IS A TEST. */
?>string.tolower
Use of this filter is equivalent to processing all stream data through the strtolower() function.
Example #3 string.tolower
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.tolower');
fwrite($fp, "This is a test.\n");
/* Outputs: this is a test. */
?>string.strip_tags
Use of this filter is equivalent to processing all stream data through the strip_tags() function. It accepts parameters in one of two forms: Either as a string containing a list of tags similar to the second parameter of the strip_tags() function, or as an array of tag names.
This feature has been DEPRECATED as of PHP 7.3.0. Relying on this feature is highly discouraged.
Example #4 string.strip_tags
<?php
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, "<b><i><u>");
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs: bolded text enlarged to a level 1 heading */
$fp = fopen('php://output', 'w');
stream_filter_append($fp, 'string.strip_tags', STREAM_FILTER_WRITE, array('b','i','u'));
fwrite($fp, "<b>bolded text</b> enlarged to a <h1>level 1 heading</h1>\n");
fclose($fp);
/* Outputs: bolded text enlarged to a level 1 heading */
?><?php
$stream = fopen('php://temp', 'w+');
fwrite($stream, 'order-42');
rewind($stream);
stream_filter_append($stream, 'string.toupper', STREAM_FILTER_READ);
echo stream_get_contents($stream), "\n";
fclose($stream);
Ожидаемый результат
ORDER-42
Фильтр не изменяет уже сохранённый источник: он преобразует байты на пути чтения. Доступность имени проверяют через stream_get_filters().
Поддерживаемые транспорты сокетов
Транспорт задаёт канал сокета, а прикладной протокол — смысл сообщений поверх него. TCP не превращает данные в HTTP, TLS не проверяет бизнес-права, UDP не гарантирует доставку. До подключения задают timeout и проверяют ошибку.
Полный официальный договор страницы
Ниже сохранён официальный русский текст и структура из зафиксированного архива PHP Manual. Отдельные ещё не переведённые страницы официального русского архива могут оставаться на английском.
Список включает информацию о встроенных в PHP транспортах для работы с сокетами. Синтаксис транспортов аналогичен схемам URL-адресов. Транспорты применяют с функциями, которые взаимодействуют с сокетами на основе потоков, — например fsockopen(), — и функцией stream_socket_client(), которая устанавливает соединение с интернет- и Unix-сокетами. Транспорты, которые перечисляет список, не применяют с функциями модуля Socket.
Список транспортов, установленных в текущей версии PHP, возвращает функция stream_get_transports().
Нормативный английский оригинал из frozen baseline
Этот слой сохраняет полный договор, если перевод отстаёт. Источник: английский нормативный оригинал.
The following is a list of the various URL style socket transports that PHP has built-in for use with the streams based socket functions such as fsockopen(), and stream_socket_client(). These transports do not apply to the Socket Functions of the Sockets extension.
For a list of transports installed in your version of PHP use stream_get_transports().
TCP, UDP, SSL и TLS
Транспорт задаёт канал сокета, а прикладной протокол — смысл сообщений поверх него. TCP не превращает данные в HTTP, TLS не проверяет бизнес-права, UDP не гарантирует доставку. До подключения задают timeout и проверяют ошибку.
Полный официальный договор страницы
Ниже сохранён официальный русский текст и структура из зафиксированного архива PHP Manual. Отдельные ещё не переведённые страницы официального русского архива могут оставаться на английском.
Транспорты для сокетов интернет-домена: ssl://, tls://,
sslv2:// и sslv3://.
Замечание:
Транспорты
sslv2://иsslv3://устарели. Документацию к этим транспортам сохранили только в целях обратной совместимости.
Замечание:
Функции автоматически выберут транспорт
tcp://, если другой не указали.
127.0.0.1fe80::1www.example.comtcp://127.0.0.1tcp://fe80::1tcp://www.example.comudp://www.example.comssl://www.example.comtls://www.example.com
Наряду с целевым адресом сокеты интернет-домена ожидают номер порта. При работе с функцией fsockopen() порт указывается вторым параметром и поэтому не влияет на формирование URL-адреса транспорта. При работе с функцией stream_socket_client() и другими функциями для работы с потоками, как и при работе с традиционными URL-адресами, номер порта указывается как суффикс — через двоеточие в конце транспортного URL-адреса.
tcp://127.0.0.1:80tcp://[fe80::1]:80tcp://www.example.com:80
Замечание: Числовые IPv6-адреса с номерами портов
Хотя во втором примере IPv4-адреса и имя хоста не изменились, за исключением добавления номера порта после двоеточия, IPv6-адрес обрамили квадратными скобками:
[fe80::1]. Квадратные скобки помогают отличать двоеточия в IPv6-адресе и двоеточие, которое отделяет номер порта.
Транспорты ssl:// и tls://,
которые доступны, только если PHP скомпилировали с поддержкой модуля openssl, —
расширяют транспорт tcp:// для включения SSL-шифрования.
Транспорт ssl:// попытается согласовать безопасное SSL/TLS-соединение
на основе протоколов и алгоритмов шифрования, доступных клиенту и удалённому хосту.
Конкретные протоколы определяются
конфигурацией библиотеки OpenSSL и параметрами
функции stream_context_create()
наподобие опции ssl.crypto_method.
Протоколы SSLv2 и SSLv3 устарели и небезопасны. Разработчики PHP и библиотеки OpenSSL больше не включают поддержку этих версий по умолчанию и настоятельно не рекомендуют обмениваться данным по устаревшим протоколам.
Нормативный английский оригинал из frozen baseline
Этот слой сохраняет полный договор, если перевод отстаёт. Источник: английский нормативный оригинал.
ssl://, tls://,
sslv2:// & sslv3://.
Note:
The
sslv2://andsslv3://transports are obsolete and should not be used. They are documented for backward compatibility only.
Note:
If no transport is specified,
tcp://will be assumed.
127.0.0.1fe80::1www.example.comtcp://127.0.0.1tcp://fe80::1tcp://www.example.comudp://www.example.comssl://www.example.comtls://www.example.com
Internet Domain sockets expect a port number in addition to a target address. In the case of fsockopen() this is specified in a second parameter and therefore does not impact the formatting of transport URL. With stream_socket_client() and related functions as with traditional URLs however, the port number is specified as a suffix of the transport URL delimited by a colon.
tcp://127.0.0.1:80tcp://[fe80::1]:80tcp://www.example.com:80
Note: IPv6 numeric addresses with port numbers
In the second example above, while the IPv4 and hostname examples are left untouched apart from the addition of their colon and portnumber, the IPv6 address is wrapped in square brackets:
[fe80::1]. This is to distinguish between the colons used in an IPv6 address and the colon used to delimit the portnumber.
The ssl:// and tls:// transports
(available only when openssl support is compiled into PHP) are extensions
of the tcp:// transport which include SSL encryption.
ssl:// will attempt to negotiate a secure SSL/TLS
connection depending on the capabilities and preferences of both the
client and the remote host. The actual protocols that may be used are
determined by the OpenSSL configuration and by any options provided
through stream_context_create(), such as
ssl.crypto_method.
The SSLv2 and SSLv3 protocols are obsolete and insecure. Their use is strongly discouraged and they are no longer enabled by default in modern versions of PHP and OpenSSL.
<?php
$target = parse_url('tcp://127.0.0.1:8080');
echo $target['scheme'], "\n";
echo $target['host'], ':', $target['port'], "\n";
Ожидаемый результат
tcp
127.0.0.1:8080
parse_url разбирает строку, но не открывает сокет и не доказывает доступность сервиса. Реальное подключение требует timeout и обработки ошибки.
Unix и UDG сокеты
Транспорт задаёт канал сокета, а прикладной протокол — смысл сообщений поверх него. TCP не превращает данные в HTTP, TLS не проверяет бизнес-права, UDP не гарантирует доставку. До подключения задают timeout и проверяют ошибку.
Полный официальный договор страницы
Ниже сохранён официальный русский текст и структура из зафиксированного архива PHP Manual. Отдельные ещё не переведённые страницы официального русского архива могут оставаться на английском.
Транспорты для сокетов Unix-домена: unix://
и udg://
unix:///tmp/mysockudg:///tmp/mysock
Транспорт unix:// открывает доступ к соединению с сокетом на основе потока в Unix-домене,
а udg:// предоставляет альтернативный транспорт
к сокету в домене Unix — через протокол UDP.
Сокеты Unix-домена, в отличие от сокетов интернет-домена, не ожидают номер порта.
При работе с функцией fsockopen()
для параметра portno требуется установить значение 0.
Замечание:
ОС Windows не поддерживают сокеты домена Unix.
Нормативный английский оригинал из frozen baseline
Этот слой сохраняет полный договор, если перевод отстаёт. Источник: английский нормативный оригинал.
unix:// and
udg://.
unix:///tmp/mysockudg:///tmp/mysock
unix:// provides access to a socket stream
connection in the Unix domain. udg:// provides
an alternate transport to a Unix domain socket using the user datagram
protocol.
Unix domain sockets, unlike Internet domain sockets, do not expect
a port number. In the case of fsockopen() the
portno parameter should be set to 0.
Note:
Unix domain sockets are not supported on Windows.
Фильтр, транспорт и прикладной протокол — разные уровни
Фильтр меняет поток байтов. Транспорт доставляет байты между endpoints. HTTP, SMTP или собственный формат определяет смысл сообщения. Ошибка на каждом уровне диагностируется отдельно: недоступное имя фильтра, отказ соединения, TLS-проверка, timeout, затем неверный ответ протокола.
Источники и обсуждения
Код и руководство с собой
Скачайте самостоятельные примеры с исходными данными, инструкциями и ожидаемыми результатами. Примеры HTTP и фрагменты для проекта помечены отдельно: им нужно указанное окружение.
Код не исполняется на сайте. Скачайте нужный пример и запускайте его в своём локальном окружении.
Материалы сверены 2026-10-12. Примеры и объяснения написаны для этого руководства; источники и обсуждения доступны в каждой главе.


