PHP Streams
Streams are the way of generalizing files, networks, data compression, and other operations which share a common set of functions and uses.
In its simplest definition, a stream is a resource object which exhibits streamable behavior.
That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary location within the stream.
A wrapper is an additional code that tells the stream how to handle specific protocols/encodings.
For example, the http wrapper knows how to translate a URL into an HTTP/1.0 request for a file on a remote server.
There are many wrappers built into PHP by default (See Supported Protocols and Wrappers), and additional, custom wrappers may be added either within a PHP script using stream_wrapper_register(), or directly from an extension using the API Reference in Working with streams.
Because any variety of wrappers may be added to PHP, there is no set limit on what can be done with them.
To access the list of currently registered wrappers, use stream_get_wrappers().
An example for reading/writing global variables
<?php
class VariableStream {
var $position;
var $varname;
function stream_open($path, $mode, $options, &$opened_path)
{
$url = parse_url($path);
$this->varname = $url["host"];
$this->position = 0;
return true;
}
function stream_read($count)
{
$ret = substr($GLOBALS[$this->varname], $this->position, $count);
$this->position += strlen($ret);
return $ret;
}
function stream_write($data)
{
$left = substr($GLOBALS[$this->varname], 0, $this->position);
$right = substr($GLOBALS[$this->varname], $this->position + strlen($data));
$GLOBALS[$this->varname] = $left . $data . $right;
$this->position += strlen($data);
return strlen($data);
}
function stream_tell()
{
return $this->position;
}
function stream_eof()
{
return $this->position >= strlen($GLOBALS[$this->varname]);
}
function stream_seek($offset, $whence)
{
switch ($whence) {
case SEEK_SET:
if ($offset < strlen($GLOBALS[$this->varname]) && $offset >= 0) {
$this->position = $offset;
return true;
} else {
return false;
}
break;
case SEEK_CUR:
if ($offset >= 0) {
$this->position += $offset;
return true;
} else {
return false;
}
break;
case SEEK_END:
if (strlen($GLOBALS[$this->varname]) + $offset >= 0) {
$this->position = strlen($GLOBALS[$this->varname]) + $offset;
return true;
} else {
return false;
}
break;
default:
return false;
}
}
function stream_metadata($path, $option, $var)
{
if($option == STREAM_META_TOUCH) {
$url = parse_url($path);
$varname = $url["host"];
if(!isset($GLOBALS[$varname])) {
$GLOBALS[$varname] = '';
}
return true;
}
return false;
}
}
stream_wrapper_register("var", "VariableStream")
or die("Failed to register protocol");
$myvar = "";
$fp = fopen("var://myvar", "r+");
fwrite($fp, "line1\n");
fwrite($fp, "line2\n");
fwrite($fp, "line3\n");
rewind($fp);
while (!feof($fp)) {
echo fgets($fp);
}
fclose($fp);
var_dump($myvar);
?>
Output
line1
line2
line3
string(18) "line1
line2
line3
"
Requirements
No external libraries are needed to build this extension.
Installation
Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.
Run-time Configuration
This extension has no configuration directives defined in php.ini.
Predefined Constants
This Streams extension also provided some predefined constants.
In order to use this extension has either been compiled into PHP or dynamically loaded at runtime.
-
STREAM_FILTER_READ
-
* Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when reading
-
-
STREAM_FILTER_WRITE
-
* Used with stream_filter_append() and stream_filter_prepend() to indicate that the specified filter should only be applied when writing
-
-
STREAM_FILTER_ALL
-
* This constant is equivalent to STREAM_FILTER_READ | STREAM_FILTER_WRITE
-
-
PSFS_PASS_ON
-
* Return Code indicating that the userspace filter returned buckets in $out.
-
-
PSFS_FEED_ME
-
* Return Code indicating that the userspace filter did not return buckets in $out (i.e. No data available).
-
-
PSFS_ERR_FATAL
-
* Return Code indicating that the userspace filter encountered an unrecoverable error (i.e. Invalid data received).
-
-
PSFS_FLAG_NORMAL
-
Regular read/write.
-
-
PSFS_FLAG_FLUSH_INC
-
An incremental flush.
-
-
PSFS_FLAG_FLUSH_CLOSE
-
Final flush prior to closing.
-
-
STREAM_USE_PATH
-
Flag indicating if the stream used the include path.
-
-
STREAM_REPORT_ERRORS
-
Flag indicating if the wrapper is responsible for raising errors using trigger_error() during the opening of the stream.
-
If this flag is not set, you should not raise any errors.
-
-
STREAM_CLIENT_ASYNC_CONNECT
-
* Open client socket asynchronously.
-
This option must be used together with the STREAM_CLIENT_CONNECT flag.
-
Used with stream_socket_client().
-
-
STREAM_CLIENT_CONNECT
-
* Open client socket connection.
-
Client sockets should always include this flag.
-
Used with stream_socket_client().
-
-
STREAM_CLIENT_PERSISTENT
-
* Client socket opened with stream_socket_client() should remain persistent between page loads.
-
-
STREAM_SERVER_BIND
-
* Tells a stream created with stream_socket_server() to bind to the specified target.
-
Server sockets should always include this flag.
-
-
STREAM_SERVER_LISTEN
-
* Tells a stream created with stream_socket_server() and bound using the STREAM_SERVER_BIND flag to start listening on the socket.
-
Connection-orientated transports (such as TCP) must use this flag, otherwise, the server socket will not be enabled.
-
Using this flag for connect-less transports (such as UDP) is an error.
-
-
STREAM_NOTIFY_RESOLVE
-
* A remote address required for this stream has been resolved, or the resolution failed.
-
See severity for an indication of which happened.
-
-
STREAM_NOTIFY_CONNECT
-
A connection with an external resource has been established.
-
-
STREAM_NOTIFY_AUTH_REQUIRED
-
Additional authorization is required to access the specified resource.
-
Typical issued with a severity level of STREAM_NOTIFY_SEVERITY_ERR.
-
-
STREAM_NOTIFY_MIME_TYPE_IS
-
The mime-type of resource has been identified, refer to the message for a description of the discovered type.
-
-
STREAM_NOTIFY_FILE_SIZE_IS
-
The size of the resource has been discovered.
-
-
STREAM_NOTIFY_REDIRECTED
-
The external resource has redirected the stream to an alternate location. Refer to message.
-
-
STREAM_NOTIFY_PROGRESS
-
Indicates current progress of the stream transfer in bytes_transferred and possibly bytes_max as well.
-
-
STREAM_NOTIFY_COMPLETED
-
* There is no more data available on the stream.
-
-
STREAM_NOTIFY_FAILURE
-
A generic error occurred on the stream, consult message, and message_code for details.
-
-
STREAM_NOTIFY_AUTH_RESULT
-
The authorization has been completed (with or without success).
-
-
STREAM_NOTIFY_SEVERITY_INFO
-
Normal, non-error related, notification.
-
-
STREAM_NOTIFY_SEVERITY_WARN
-
Non-critical error condition. Processing may continue.
-
-
STREAM_NOTIFY_SEVERITY_ERR
-
A critical error occurred. Processing cannot continue.
-
-
STREAM_IPPROTO_ICMP
-
+ Provides an ICMP socket.
-
-
STREAM_IPPROTO_IP
-
+ Provides an IP socket.
-
-
STREAM_IPPROTO_RAW
-
+ Provides a RAW socket.
-
-
STREAM_IPPROTO_TCP
-
+ Provides a TCP socket.
-
-
STREAM_IPPROTO_UDP
-
+ Provides a UDP socket.
-
-
STREAM_PF_INET
-
+ Internet Protocol Version 4 (IPv4).
-
-
STREAM_PF_INET6
-
+ Internet Protocol Version 6 (IPv6).
-
-
STREAM_PF_UNIX
-
+ Unix system internal protocols.
-
-
STREAM_SOCK_DGRAM
-
+ Provides datagrams, which are connectionless messages (UDP, for example).
-
-
STREAM_SOCK_RAW
-
+ Provides a raw socket, which provides access to internal network protocols and interfaces.
-
Usually, this type of socket is just available to the root user.
-
-
STREAM_SOCK_RDM
-
+ Provides an RDM (Reliably delivered messages) socket.
-
-
STREAM_SOCK_SEQPACKET
-
+ Provides a sequenced packet stream socket.
-
-
STREAM_SOCK_STREAM
-
+ Provides sequenced, two-way byte streams with a transmission mechanism for out-of-band data (TCP, for example).
-
-
STREAM_SHUT_RD
-
Used with stream_socket_shutdown() to disable further receptions. Added in PHP 5.2.1.
-
-
STREAM_SHUT_WR
-
Used with stream_socket_shutdown() to disable further transmissions. Added in PHP 5.2.1.
-
-
STREAM_SHUT_RDWR
-
Used with stream_socket_shutdown() to disable further receptions and transmissions. Added in PHP 5.2.1.
-
-
STREAM_CAST_FOR_SELECT
-
Stream casting, for when stream_select() is calling stream_cast().
-
-
STREAM_CAST_AS_STREAM
-
Stream casting, when stream_cast() is called otherwise (see above).
-
-
STREAM_META_TOUCH
-
Used with stream_metadata(), to specify touch() call.
-
-
STREAM_META_OWNER
-
Used with stream_metadata(), to specify chown() call.
-
-
STREAM_META_OWNER_NAME
-
Used with stream_metadata(), to specify chown() call.
-
-
STREAM_META_GROUP
-
Used with stream_metadata(), to specify chgrp() call.
-
-
STREAM_META_GROUP_NAME
-
Used with stream_metadata(), to specify chgrp() call.
-
-
STREAM_META_ACCESS
-
Used with stream_metadata(), to specify chmod() call.
-
Stream Functions
-
set_socket_blocking — Alias of stream_set_blocking
-
stream_bucket_append — Append bucket to brigade
-
stream_bucket_make_writeable — Return a bucket object from the brigade for operating on
-
stream_bucket_new — Create a new bucket for use on the current stream
-
stream_bucket_prepend — Prepend bucket to brigade
-
stream_context_create — Creates a stream context
-
stream_context_get_default — Retrieve the default stream context
-
stream_context_get_options — Retrieve options for a stream/wrapper/context
-
stream_context_get_params — Retrieves parameters from a context
-
stream_context_set_default — Set the default stream context
-
stream_context_set_option — Sets an option for a stream/wrapper/context
-
stream_context_set_params — Set parameters for a stream/wrapper/context
-
stream_copy_to_stream — Copies data from one stream to another
-
stream_filter_append — Attach a filter to a stream
-
stream_filter_prepend — Attach a filter to a stream
-
stream_filter_register — Register a user-defined stream filter
-
stream_filter_remove — Remove a filter from a stream
-
stream_get_contents — Reads remainder of a stream into a string
-
stream_get_filters — Retrieve the list of registered filters
-
stream_get_line — Gets line from stream resource up to a given delimiter
-
stream_get_meta_data — Retrieves header/metadata from streams/file pointers
-
stream_get_transports — Retrieve list of registered socket transports
-
stream_get_wrappers — Retrieve list of registered streams
-
stream_is_local — Checks if a stream is a local stream
-
stream_isatty — Check if a stream is a TTY
-
stream_notification_callback — A callback function for the notification context parameter
-
stream_register_wrapper — Alias of stream_wrapper_register
-
stream_resolve_include_path — Resolve filename against the include path
-
stream_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by tv_sec and tv_usec
-
stream_set_blocking — Set blocking/non-blocking mode on a stream
-
stream_set_chunk_size — Set the stream chunk size
-
stream_set_read_buffer — Set read file buffering on the given stream
-
stream_set_timeout — Set timeout period on a stream
-
stream_set_write_buffer — Sets write file buffering on the given stream
-
stream_socket_accept — Accept a connection on a socket created by stream_socket_server
-
stream_socket_client — Open Internet or Unix domain socket connection
-
stream_socket_enable_crypto — Turns encryption on/off on an already connected socket
-
stream_socket_get_name — Retrieve the name of the local or remote sockets
-
stream_socket_pair — Creates a pair of connected, indistinguishable socket streams
-
stream_socket_recvfrom — Receives data from a socket, connected or not
-
stream_socket_sendto — Sends a message to a socket, whether it is connected or not
-
stream_socket_server — Create an Internet or Unix domain server socket
-
stream_socket_shutdown — Shutdown a full-duplex connection
-
stream_supports_lock — Tells whether the stream supports locking
-
stream_wrapper_register — Register a URL wrapper implemented as a PHP class
-
stream_wrapper_restore — Restores a previously unregistered built-in wrapper
-
stream_wrapper_unregister — Unregister a URL wrapper
Streams Predefined Classes
php_user_filter
-
php_user_filter::filter — Called when applying the filter
-
php_user_filter::onClose — Called when closing the filter
-
php_user_filter::onCreate — Called when creating the filter
streamWrapper
-
streamWrapper::__construct — Constructs a new stream wrapper
-
streamWrapper::__destruct — Destructs an existing stream wrapper
-
streamWrapper::dir_closedir — Close directory handle
-
streamWrapper::dir_opendir — Open directory handle
-
streamWrapper::dir_readdir — Read entry from directory handle
-
streamWrapper::dir_rewinddir — Rewind directory handle
-
streamWrapper::mkdir — Create a directory
-
streamWrapper::rename — Renames a file or directory
-
streamWrapper::rmdir — Removes a directory
-
streamWrapper::stream_cast — Retrieve the underlaying resource
-
streamWrapper::stream_close — Close a resource
-
streamWrapper::stream_eof — Tests for end-of-file on a file pointer
-
streamWrapper::stream_flush — Flushes the output
-
streamWrapper::stream_lock — Advisory file locking
-
streamWrapper::stream_metadata — Change stream metadata
-
streamWrapper::stream_open — Opens file or URL
-
streamWrapper::stream_read — Read from stream
-
streamWrapper::stream_seek — Seeks to specific location in a stream
-
streamWrapper::stream_set_option — Change stream options
-
streamWrapper::stream_stat — Retrieve information about a file resource
-
streamWrapper::stream_tell — Retrieve the current position of a stream
-
streamWrapper::stream_truncate — Truncate stream
-
streamWrapper::stream_write — Write to stream
-
streamWrapper::unlink — Delete a file
-
streamWrapper::url_stat — Retrieve information about a file