Streams

目录

简介

Children of this class are passed to stream_filter_register.

类摘要

php_user_filter

class php_user_filter {

/* 属性 */

public $filtername ;

public $params ;

/* 方法 */

public int filter ( resource $in , resource $out , int &$consumed , bool $closing )

public void onClose ( void )

public bool onCreate ( void )

}

属性

filtername
Name of the filter registered by stream_filter_append.

params

php_user_filter::filter

Called when applying the filter

说明

public int php_user_filter::filter ( resource $in , resource $out , int &$consumed , bool $closing )

This method is called whenever data is read from or written to the attached stream (such as with fread or fwrite).

参数

in
in is a resource pointing to a bucket brigade which contains one or more bucket objects containing data to be filtered.

out
out is a resource pointing to a second bucket brigade into which your modified buckets should be placed.

consumed
consumed, which must always be declared by reference, should be incremented by the length of the data which your filter reads in and alters. In most cases this means you will increment consumed by $bucket->datalen for each $bucket.

closing
If the stream is in the process of closing (and therefore this is the last pass through the filterchain), the closing parameter will be set to TRUE.

返回值

The filter method must return one of three values upon completion.

Return ValueMeaning
PSFS_PASS_ONFilter processed successfully with data available in the out bucket brigade.
PSFS_FEED_MEFilter processed successfully, however no data was available to return. More data is required from the stream or prior filter.
PSFS_ERR_FATAL (default)The filter experienced an unrecoverable error and cannot continue.

php_user_filter::onClose

Called when closing the filter

说明

public void php_user_filter::onClose ( void )

This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed after the flush method is called. If any resources were allocated or initialized during onCreate() this would be the time to destroy or dispose of them.

参数

此函数没有参数。

返回值

Return value is ignored.

php_user_filter::onCreate

Called when creating the filter

说明

public bool php_user_filter::onCreate ( void )

This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it.

When your filter is first instantiated, and yourfilter->onCreate() is called, a number of properties will be available as shown in the table below.

PropertyContents
FilterClass->filternameA string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used.
FilterClass->paramsThe contents of the params parameter passed to stream_filter_append or stream_filter_prepend.
FilterClass->streamThe stream resource being filtered. Maybe available only during filter calls when the closing parameter is set to FALSE.

参数

此函数没有参数。

返回值

Your implementation of this method should return FALSE on failure, or TRUE on success.

简介

Allows you to implement your own protocol handlers and streams for use with all the other filesystem functions (such as fopen, fread etc.).

Note:

This is NOT a real class, only a prototype of how a class defining its own protocol should be.

Note:

Implementing the methods in other ways than described here can lead to undefined behaviour.

An instance of this class is initialized as soon as a stream function tries to access the protocol it is associated with.

类摘要

streamWrapper

class streamWrapper {

/* 属性 */

public resource $context ;

/* 方法 */

__construct ( void )

__destruct ( void )

public bool dir_closedir ( void )

public bool dir_opendir ( string $path , int $options )

public string dir_readdir ( void )

public bool dir_rewinddir ( void )

public bool mkdir ( string $path , int $mode , int $options )

public bool rename ( string $path_from , string $path_to )

public bool rmdir ( string $path , int $options )

public resource stream_cast ( int $cast_as )

public void stream_close ( void )

public bool stream_eof ( void )

public bool stream_flush ( void )

public bool stream_lock ( int $operation )

public bool stream_metadata ( string $path , int $option , mixed $value )

public bool stream_open ( string $path , string $mode , int $options , string &$opened_path )

public string stream_read ( int $count )

public bool stream_seek ( int $offset , int $whence = SEEK_SET )

public bool stream_set_option ( int $option , int $arg1 , int $arg2 )

public array stream_stat ( void )

public int stream_tell ( void )

public bool stream_truncate ( int $new_size )

public int stream_write ( string $data )

public bool unlink ( string $path )

public array url_stat ( string $path , int $flags )

}

属性

resource context
The current context, or NULL if no context was passed to the caller function.

Use the stream_context_get_options to parse the context.

Note:

This property must be public so PHP can populate it with the actual context resource.

参见

  • stream_wrapper_register
  • stream_wrapper_unregister
  • stream_wrapper_restore

streamWrapper::__construct

Constructs a new stream wrapper

说明

streamWrapper::__construct ( void )

Called when opening the stream wrapper, right before streamWrapper::stream_open.

参数

此函数没有参数。

streamWrapper::__destruct

Destructs an existing stream wrapper

说明

streamWrapper::__destruct ( void )

Called when closing the stream wrapper, right before streamWrapper::stream_flush.

参数

此函数没有参数。

streamWrapper::dir_closedir

Close directory handle

说明

public bool streamWrapper::dir_closedir ( void )

This method is called in response to closedir.

Any resources which were locked, or allocated, during opening and use of the directory stream should be released.

参数

此函数没有参数。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • closedir
  • streamWrapper::dir_opendir

streamWrapper::dir_opendir

Open directory handle

说明

public bool streamWrapper::dir_opendir ( string $path , int $options )

This method is called in response to opendir.

参数

path
Specifies the URL that was passed to opendir.

Note:

The URL can be broken apart with class="function">parse_url.

options
Whether or not to enforce safe_mode (0x04).

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • opendir
  • streamWrapper::dir_closedir
  • parse_url

streamWrapper::dir_readdir

Read entry from directory handle

说明

public string streamWrapper::dir_readdir ( void )

This method is called in response to readdir.

参数

此函数没有参数。

返回值

Should return string representing the next filename, or FALSE if there is no next file.

Note:

The return value will be casted to string.

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

范例

示例 #1 Listing files from tar archives

<?php
class streamWrapper {
    protected $fp;

    public function dir_opendir($path, $options) {
        $url = parse_url($path);

        $path = $url["host"] . $url["path"];

        if (!is_readable($path)) {
            trigger_error("$path isn't readable for me", E_USER_NOTICE);
            return false;
        }
        if (!is_file($path)) {
            trigger_error("$path isn't a file", E_USER_NOTICE);
            return false;
        }

        $this->fp = fopen($path, "rb");
        return true;
    }

    public function dir_readdir() {
        // Extract the header for this entry
        $header      = fread($this->fp, 512);
        $data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/a8checksum/a1filetype/a100link/a100linkedfile", $header);

        // Trim the filename and filesize
        $filename    = trim($data["filename"]);

        // No filename? We are the end of the archive
        if (!$filename) {
            return false;
        }

        $octal_bytes = trim($data["size"]);
        // Filesize is defined in octects
        $bytes       = octdec($octal_bytes);

        // tar rounds up filesizes up to multiple of 512 bytes (zero filled)
        $rest        = $bytes % 512;
        if ($rest > 0) {
            $bytes      += 512 - $rest;
        }

        // Seek over the file
        fseek($this->fp, $bytes, SEEK_CUR);

        return $filename;
    }

    public function dir_closedir() {
        return fclose($this->fp);
    }

    public function dir_rewinddir() {
        return fseek($this->fp, 0, SEEK_SET);
    }
}

stream_wrapper_register("tar", "streamWrapper");
$handle = opendir("tar://example.tar");
while (false !== ($file = readdir($handle))) {
    var_dump($file);
}

echo "Rewinding..\n";
rewind($handle);
var_dump(readdir($handle));

closedir($handle);
?>

以上例程的输出类似于:

string(13) "construct.xml"
string(16) "dir-closedir.xml"
string(15) "dir-opendir.xml"
string(15) "dir-readdir.xml"
string(17) "dir-rewinddir.xml"
string(9) "mkdir.xml"
string(10) "rename.xml"
string(9) "rmdir.xml"
string(15) "stream-cast.xml"
string(16) "stream-close.xml"
string(14) "stream-eof.xml"
string(16) "stream-flush.xml"
string(15) "stream-lock.xml"
string(15) "stream-open.xml"
string(15) "stream-read.xml"
string(15) "stream-seek.xml"
string(21) "stream-set-option.xml"
string(15) "stream-stat.xml"
string(15) "stream-tell.xml"
string(16) "stream-write.xml"
string(10) "unlink.xml"
string(12) "url-stat.xml"
Rewinding..
string(13) "construct.xml"

参见

  • readdir

streamWrapper::dir_rewinddir

Rewind directory handle

说明

public bool streamWrapper::dir_rewinddir ( void )

This method is called in response to rewinddir.

Should reset the output generated by streamWrapper::dir_readdir. i.e.: The next call to streamWrapper::dir_readdir should return the first entry in the location returned by streamWrapper::dir_opendir.

参数

此函数没有参数。

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • rewinddir
  • streamWrapper::dir_readdir

streamWrapper::mkdir

Create a directory

说明

public bool streamWrapper::mkdir ( string $path , int $mode , int $options )

This method is called in response to mkdir.

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support creating directories.

参数

path
Directory which should be created.

mode
The value passed to mkdir.

options
A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

注释

Note:

当合法的上下文传递给调用函数时,属性 streamWrapper::$context 会被改变。

参见

  • mkdir
  • streamwrapper::rmdir

streamWrapper::rename

Renames a file or directory

说明

public bool streamWrapper::rename ( string $path_from , string $path_to )

This method is called in response to rename.

Should attempt to rename path_from to path_to

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support renaming files.

参数

path_from
The URL to the current file.

path_to
The URL which the path_from should be renamed to.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

注释

Note:

当合法的上下文传递给调用函数时,属性 streamWrapper::$context 会被改变。

参见

  • rename

streamWrapper::rmdir

Removes a directory

说明

public bool streamWrapper::rmdir ( string $path , int $options )

This method is called in response to rmdir.

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing directories.

参数

path
The directory URL which should be removed.

options
A bitwise mask of values, such as STREAM_MKDIR_RECURSIVE.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

注释

Note:

当合法的上下文传递给调用函数时,属性 streamWrapper::$context 会被改变。

参见

  • rmdir
  • streamwrapper::mkdir
  • streamwrapper::unlink

streamWrapper::stream_cast

Retrieve the underlaying resource

说明

public resource streamWrapper::stream_cast ( int $cast_as )

This method is called in response to stream_select.

参数

cast_as
Can be STREAM_CAST_FOR_SELECT when stream_select is calling stream_cast or STREAM_CAST_AS_STREAM when stream_cast is called for other uses.

返回值

Should return the underlying stream resource used by the wrapper, or FALSE.

参见

  • stream_select

streamWrapper::stream_close

Close a resource

说明

public void streamWrapper::stream_close ( void )

This method is called in response to fclose.

All resources that were locked, or allocated, by the wrapper should be released.

参数

此函数没有参数。

返回值

没有返回值。

参见

  • fclose
  • streamWrapper::dir_closedir

streamWrapper::stream_eof

Tests for end-of-file on a file pointer

说明

public bool streamWrapper::stream_eof ( void )

This method is called in response to feof.

参数

此函数没有参数。

返回值

Should return TRUE if the read/write position is at the end of the stream and if no more data is available to be read, or FALSE otherwise.

注释

Warning

When reading the whole file (for example, with file_get_contents), PHP will call streamWrapper::stream_read followed by streamWrapper::stream_eof in a loop but as long as streamWrapper::stream_read returns a non-empty string, the return value of streamWrapper::stream_eof is ignored.

参见

  • feof

streamWrapper::stream_flush

Flushes the output

说明

public bool streamWrapper::stream_flush ( void )

This method is called in response to fflush and when the stream is being closed while any unflushed data has been written to it before.

If you have cached data in your stream but not yet stored it into the underlying storage, you should do so now.

参数

此函数没有参数。

返回值

Should return TRUE if the cached data was successfully stored (or if there was no data to store), or FALSE if the data could not be stored.

注释

Note:

If not implemented, FALSE is assumed as the return value.

参见

  • fflush

streamWrapper::stream_lock

Advisory file locking

说明

public bool streamWrapper::stream_lock ( int $operation )

This method is called in response to flock, when file_put_contents (when flags contains LOCK_EX), stream_set_blocking and when closing the stream (LOCK_UN).

参数

operation
operation is one of the following:

  • LOCK_SH to acquire a shared lock (reader).
  • LOCK_EX to acquire an exclusive lock (writer).
  • LOCK_UN to release a lock (shared or exclusive).
  • LOCK_NB if you don't want flock to block while locking. (not supported on Windows)

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

Emits E_WARNING if call to this method fails (i.e. not implemented).

参见

  • stream_set_blocking
  • flock

streamWrapper::stream_metadata

Change stream metadata

说明

public bool streamWrapper::stream_metadata ( string $path , int $option , mixed $value )

This method is called to set metadata on the stream. It is called when one of the following functions is called on a stream URL:

  • touch
  • chmod
  • chown
  • chgrp

Please note that some of these operations may not be available on your system.

参数

path
The file path or URL to set metadata. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

option
One of:

  • STREAM_META_TOUCH (The method was called in response to touch)
  • STREAM_META_OWNER_NAME (The method was called in response to chown with string parameter)
  • STREAM_META_OWNER (The method was called in response to chown)
  • STREAM_META_GROUP_NAME (The method was called in response to chgrp)
  • STREAM_META_GROUP (The method was called in response to chgrp)
  • STREAM_META_ACCESS (The method was called in response to chmod)

value
If option is

  • STREAM_META_TOUCH: Array consisting of two arguments of the touch function.
  • STREAM_META_OWNER_NAME or STREAM_META_GROUP_NAME: The name of the owner user/group as string.
  • STREAM_META_OWNER or STREAM_META_GROUP: The value owner user/group argument as integer.
  • STREAM_META_ACCESS: The argument of the chmod as integer.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE。 If option is not implemented, FALSE should be returned.

参见

  • touch
  • chmod
  • chown
  • chgrp

streamWrapper::stream_open

Opens file or URL

说明

public bool streamWrapper::stream_open ( string $path , string $mode , int $options , string &$opened_path )

This method is called immediately after the wrapper is initialized (f.e. by fopen and file_get_contents).

参数

path
Specifies the URL that was passed to the original function.

Note:

The URL can be broken apart with class="function">parse_url. Note that only URLs delimited by :// are supported. : and :/ while technically valid URLs, are not.

mode
The mode used to open the file, as detailed for fopen.

Note:

Remember to check if the mode is valid for the path requested.

options
Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

FlagDescription
STREAM_USE_PATHIf path is relative, search for the resource using the include_path.
STREAM_REPORT_ERRORSIf this flag is set, you are responsible for raising errors using trigger_error during opening of the stream. If this flag is not set, you should not raise any errors.

opened_path
If the path is opened successfully, and STREAM_USE_PATH is set in options, opened_path should be set to the full path of the file/resource that was actually opened.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

注释

Note:

当合法的上下文传递给调用函数时,属性 streamWrapper::$context 会被改变。

参见

  • fopen
  • parse_url

streamWrapper::stream_read

Read from stream

说明

public string streamWrapper::stream_read ( int $count )

This method is called in response to fread and fgets.

Note:

Remember to update the read/write position of the stream (by the number of bytes that were successfully read).

参数

count
How many bytes of data from the current position should be returned.

返回值

If there are less than count bytes available, return as many as are available. If no more data is available, return either FALSE or an empty string.

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

Note:

If the return value is longer then count an E_WARNING error will be emitted, and excess data will be lost.

注释

Note:

streamWrapper::stream_eof is called directly after calling class="methodname">streamWrapper::stream_read to check if EOF has been reached. If not implemented, EOF is assumed.

Warning

When reading the whole file (for example, with file_get_contents), PHP will call streamWrapper::stream_read followed by streamWrapper::stream_eof in a loop but as long as streamWrapper::stream_read returns a non-empty string, the return value of streamWrapper::stream_eof is ignored.

参见

  • fread
  • fgets

streamWrapper::stream_seek

Seeks to specific location in a stream

说明

public bool streamWrapper::stream_seek ( int $offset , int $whence = SEEK_SET )

This method is called in response to fseek.

The read/write position of the stream should be updated according to the offset and whence.

参数

offset
The stream offset to seek to.

whence
Possible values:

  • SEEK_SET - Set position equal to offset bytes.
  • SEEK_CUR - Set position to current location plus offset.
  • SEEK_END - Set position to end-of-file plus offset.

返回值

Return TRUE if the position was updated, FALSE otherwise.

注释

Note:

If not implemented, FALSE is assumed as the return value.

Note:

Upon success, class="methodname">streamWrapper::stream_tell is called directly after calling class="methodname">streamWrapper::stream_seek. If class="methodname">streamWrapper::stream_tell fails, the return value to the caller function will be set to FALSE

Note:

Not all seeks operations on the stream will result in this function being called. PHP streams have read buffering enabled by default (see also stream_set_read_buffer) and seeking may be done by merely moving the buffer pointer.

参见

  • fseek

streamWrapper::stream_set_option

Change stream options

说明

public bool streamWrapper::stream_set_option ( int $option , int $arg1 , int $arg2 )

This method is called to set options on the stream.

参数

option
One of:

  • STREAM_OPTION_BLOCKING (The method was called in response to stream_set_blocking)
  • STREAM_OPTION_READ_TIMEOUT (The method was called in response to stream_set_timeout)
  • STREAM_OPTION_WRITE_BUFFER (The method was called in response to stream_set_write_buffer)

arg1
If option is

  • STREAM_OPTION_BLOCKING: requested blocking mode (1 meaning block 0 not blocking).
  • STREAM_OPTION_READ_TIMEOUT: the timeout in seconds.
  • STREAM_OPTION_WRITE_BUFFER: buffer mode (STREAM_BUFFER_NONE or STREAM_BUFFER_FULL).

arg2
If option is

  • STREAM_OPTION_BLOCKING: This option is not set.
  • STREAM_OPTION_READ_TIMEOUT: the timeout in microseconds.
  • STREAM_OPTION_WRITE_BUFFER: the requested buffer size.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE。 If option is not implemented, FALSE should be returned.

参见

  • stream_set_blocking
  • stream_set_timeout
  • stream_set_write_buffer

streamWrapper::stream_stat

Retrieve information about a file resource

说明

public array streamWrapper::stream_stat ( void )

This method is called in response to fstat.

参数

此函数没有参数。

返回值

See stat.

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

参见

  • stat
  • streamwrapper::url_stat

streamWrapper::stream_tell

Retrieve the current position of a stream

说明

public int streamWrapper::stream_tell ( void )

This method is called in response to fseek to determine the current position.

参数

此函数没有参数。

返回值

Should return the current position of the stream.

参见

  • streamWrapper::stream_tell

streamWrapper::stream_truncate

Truncate stream

说明

public bool streamWrapper::stream_truncate ( int $new_size )

Will respond to truncation, e.g., through ftruncate.

参数

new_size
The new size.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

参见

  • ftruncate

streamWrapper::stream_write

Write to stream

说明

public int streamWrapper::stream_write ( string $data )

This method is called in response to fwrite.

Note:

Remember to update the current position of the stream by number of bytes that were successfully written.

参数

data
Should be stored into the underlying stream.

Note:

If there is not enough room in the underlying stream, store as much as possible.

返回值

Should return the number of bytes that were successfully stored, or 0 if none could be stored.

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

Note:

If the return value is greater the length of data, E_WARNING will be emitted and the return value will truncated to its length.

参见

  • fwrite

streamWrapper::unlink

Delete a file

说明

public bool streamWrapper::unlink ( string $path )

This method is called in response to unlink.

Note:

In order for the appropriate error message to be returned this method should not be defined if the wrapper does not support removing files.

参数

path
The file URL which should be deleted.

返回值

成功时返回 TRUE, 或者在失败时返回 FALSE

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

注释

Note:

当合法的上下文传递给调用函数时,属性 streamWrapper::$context 会被改变。

参见

  • unlink
  • streamWrapper::rmdir

streamWrapper::url_stat

Retrieve information about a file

说明

public array streamWrapper::url_stat ( string $path , int $flags )

This method is called in response to all stat related functions, such as:

  • chmod (only when safe_mode is enabled)
  • copy
  • fileperms
  • fileinode
  • filesize
  • fileowner
  • filegroup
  • fileatime
  • filemtime
  • filectime
  • filetype
  • is_writable
  • is_readable
  • is_executable
  • is_file
  • is_dir
  • is_link
  • file_exists
  • lstat
  • stat
  • SplFileInfo::getPerms
  • SplFileInfo::getInode
  • SplFileInfo::getSize
  • SplFileInfo::getOwner
  • SplFileInfo::getGroup
  • SplFileInfo::getATime
  • SplFileInfo::getMTime
  • SplFileInfo::getCTime
  • SplFileInfo::getType
  • SplFileInfo::isWritable
  • SplFileInfo::isReadable
  • SplFileInfo::isExecutable
  • SplFileInfo::isFile
  • SplFileInfo::isDir
  • SplFileInfo::isLink
  • RecursiveDirectoryIterator::hasChildren

参数

path
The file path or URL to stat. Note that in the case of a URL, it must be a :// delimited URL. Other URL forms are not supported.

flags
Holds additional flags set by the streams API. It can hold one or more of the following values OR'd together.

FlagDescription
STREAM_URL_STAT_LINKFor resources with the ability to link to other resource (such as an HTTP Location: forward, or a filesystem symlink). This flag specified that only information about the link itself should be returned, not the resource pointed to by the link. This flag is set in response to calls to lstat, is_link, or filetype.
STREAM_URL_STAT_QUIETIf this flag is set, your wrapper should not raise any errors. If this flag is not set, you are responsible for reporting errors using the trigger_error function during stating of the path.

返回值

Should return as many elements as stat does. Unknown or unavailable values should be set to a rational value (usually 0). Pay special attention to mode as documented under stat.

错误/异常

调用此方法失败将给出 E_WARNING(未实现)。

注释

Note:

当合法的上下文传递给调用函数时,属性 streamWrapper::$context 会被改变。

参见

  • stat
  • streamwrapper::stream_stat