Php stream file name

fopen

fopen() binds a named resource, specified by filename , to a stream.

Parameters

If filename is of the form «scheme://. «, it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.

If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.

Note:

The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers ) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).

On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.

Читайте также:  Открытие больших файлов python

The mode parameter specifies the type of access you require to the stream. It may be any of the following:

A list of possible modes for fopen() using mode
mode Description
‘r’ Open for reading only; place the file pointer at the beginning of the file.
‘r+’ Open for reading and writing; place the file pointer at the beginning of the file.
‘w’ Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
‘w+’ Open for reading and writing; otherwise it has the same behavior as ‘w’ .
‘a’ Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended.
‘a+’ Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.
‘x’ Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning false and generating an error of level E_WARNING . If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call.
‘x+’ Create and open for reading and writing; otherwise it has the same behavior as ‘x’ .
‘c’ Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’ ), nor the call to this function fails (as is the case with ‘x’ ). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock() ) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
‘c+’ Open the file for reading and writing; otherwise it has the same behavior as ‘c’ .
‘e’ Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems.

Note:

Different operating system families have different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems (Mac OS Classic) used \r as the line ending character.

If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will «look funny».

Windows offers a text-mode translation flag ( ‘t’ ) which will transparently translate \n to \r\n when working with the file. In contrast, you can also use ‘b’ to force binary mode, which will not translate your data. To use these flags, specify either ‘b’ or ‘t’ as the last character of the mode parameter.

The default translation mode is ‘b’ . You can use the ‘t’ mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as old versions of notepad. You should use the ‘b’ in all other cases.

If you specify the ‘t’ flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.

Note:

For portability, it is also strongly recommended that you re-write code that uses or relies upon the ‘t’ mode so that it uses the correct line endings and ‘b’ mode instead.

Note: The mode is ignored for php://output , php://input , php://stdin , php://stdout , php://stderr and php://fd stream wrappers.

The optional third use_include_path parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.

Источник

stream_get_contents

Похожа на функцию file_get_contents() , за исключением того, что stream_get_contents() работает с уже открытым ресурсом потока и возвращает оставшуюся часть содержимого в строку размером до length байт и начиная с указанного смещения offset .

Список параметров

Ресурс потока (например, полученный при помощи функции fopen() )

Максимальное количество байт для чтения. По умолчанию null (прочитать весь оставшийся буфер).

Перейти к указанному смещению перед чтением. Если это число отрицательное, то переход не произойдёт и чтение начнётся с текущей позиции.

Возвращаемые значения

Возвращает строку или false в случае возникновения ошибки.

Список изменений

Примеры

Пример #1 Пример использования stream_get_contents()

if ( $stream = fopen ( ‘http://www.example.com’ , ‘r’ )) // вывести всю страницу начиная со смещения 10
echo stream_get_contents ( $stream , — 1 , 10 );

if ( $stream = fopen ( ‘http://www.example.net’ , ‘r’ )) // вывести первые 5 байт
echo stream_get_contents ( $stream , 5 );

Примечания

Замечание: Эта функция безопасна для обработки данных в двоичной форме.

Замечание:

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

Смотрите также

  • fgets() — Читает строку из файла
  • fread() — Бинарно-безопасное чтение файла
  • fpassthru() — Выводит все оставшиеся данные из файлового указателя

User Contributed Notes 5 notes

It is important to know that stream_get_contents behaves differently with different versions of PHP. Consider the following

$handle = fopen ( ‘file’ , ‘w+’ ); // truncate + attempt to create
fwrite ( $handle , ‘12345’ ); // file position > 0
rewind ( $handle ); // position = 0
$content = stream_get_contents ( $handle ); // file position = 0 in PHP 5.1.6, file position > 0 in PHP 5.2.17!
fwrite ( $handle , ‘6789’ );
fclose ( $handle );

/**
*
* ‘file’ content
*
* PHP 5.1.6:
* 67895
*
* PHP 5.2.17:
* 123456789
*
*/
?>

As a result, stream_get_contents() affects file position in 5.1, and do not affect file position in 5.2 or better.

In that case when stream_get_contents/fread/fgets or other stream reading functions block indefinitely your script because they don’t reached the limit of bytes to read use the socket_get_meta_data function to figure out the number of the bytes to read. It returns an array that contains a key named ‘unread_bytes’ and then pass that number to your favourite stream reading functions second parameter to read from the stream.

Maybe a good workaround to use the stream_select function, and set the socket to non-blocking mode with the use of stream_set_blocking($stream, 0). In this case the socket reading functions work properly.

When omitting the parameter $maxlength, any received bytes are stacked up until the underlying stream is not readable anymore, the the function returns that stack in one piece.

/*
* problem: stream_get_contents blocks / is very slow.
* I have tried
* 1: stream_set_blocking, doesn’t make a difference.
* 2: stream_get_meta_data[‘unread_bytes’] = ITS BUGGED, ALWAYS SAYS 0.
* 3: feof(): ALSO EFFING BLOCKING
* 4: my_stream_get_contents hack. kinda working! 😀
*/
function my_stream_get_contents ($handle, $timeout_seconds = 0.5)
$ret = «»;
// feof ALSO BLOCKS:
// while(!feof($handle))
while (true) $starttime = microtime(true);
$new = stream_get_contents($handle, 1);
$endtime = microtime(true);
if (is_string($new) && strlen($new) >= 1) $ret .= $new;
>
$time_used = $endtime — $starttime;
// var_dump(‘time_used:’,$time_used);
if (($time_used >= $timeout_seconds) || ! is_string($new) ||
(is_string($new) && strlen($new) < 1)) break;
>
>
return $ret;
>

  • Функции для работы с потоками
    • stream_​bucket_​append
    • stream_​bucket_​make_​writeable
    • stream_​bucket_​new
    • stream_​bucket_​prepend
    • stream_​context_​create
    • stream_​context_​get_​default
    • stream_​context_​get_​options
    • stream_​context_​get_​params
    • stream_​context_​set_​default
    • stream_​context_​set_​option
    • stream_​context_​set_​params
    • stream_​copy_​to_​stream
    • stream_​filter_​append
    • stream_​filter_​prepend
    • stream_​filter_​register
    • stream_​filter_​remove
    • stream_​get_​contents
    • stream_​get_​filters
    • stream_​get_​line
    • stream_​get_​meta_​data
    • stream_​get_​transports
    • stream_​get_​wrappers
    • stream_​is_​local
    • stream_​isatty
    • stream_​notification_​callback
    • stream_​register_​wrapper
    • stream_​resolve_​include_​path
    • stream_​select
    • stream_​set_​blocking
    • stream_​set_​chunk_​size
    • stream_​set_​read_​buffer
    • stream_​set_​timeout
    • stream_​set_​write_​buffer
    • stream_​socket_​accept
    • stream_​socket_​client
    • stream_​socket_​enable_​crypto
    • stream_​socket_​get_​name
    • stream_​socket_​pair
    • stream_​socket_​recvfrom
    • stream_​socket_​sendto
    • stream_​socket_​server
    • stream_​socket_​shutdown
    • stream_​supports_​lock
    • stream_​wrapper_​register
    • stream_​wrapper_​restore
    • stream_​wrapper_​unregister

    Источник

Оцените статью