Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Stream Functions

Stream Functions

Introduction

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, 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 locations within the stream.

A wrapper is additional code which 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 Appendix O, List of Supported Protocols/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 ???. Because any variety of wrapper 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().

A stream is referenced as: scheme://target

  • scheme(string) - The name of the wrapper to be used. Examples include: file, http, https, ftp, ftps, compress.zlib, compress.bz2, and php. See Appendix O, List of Supported Protocols/Wrappers for a list of PHP built-in wrappers. If no wrapper is specified, the function default is used (typically file://).
  • target - Depends on the wrapper used. For filesystem related streams this is typically a path and filename of the desired file. For network related streams this is typically a hostname, often with a path appended. Again, see Appendix O, List of Supported Protocols/Wrappers for a description of targets for built-in streams.

Stream Filters

A filter is a final piece of code which may perform operations on data as it is being read from or written to a stream. Any number of filters may be stacked onto a stream. Custom filters can be defined in a PHP script using stream_filter_register() or in an extension using the API Reference in ???. To access the list of currently registered filters, use stream_get_filters().

Stream Contexts

A context is a set of parameters and wrapper specific options which modify or enhance the behavior of a stream. Contexts are created using stream_context_create() and can be passed to most filesystem related stream creation functions (i.e. fopen(), file(), file_get_contents(), etc...).

Options can be specified when calling stream_context_create(), or later using stream_context_set_option(). A list of wrapper specific options can be found with the list of built-in wrappers (See Appendix O, List of Supported Protocols/Wrappers).

In addition, parameters may be set on a context using stream_context_set_params(). Currently the only context parameter supported by PHP is notification. The value of this parameter must be the name of a function to be called when an event occurs on a stream. The notification function called during an event should accept the following six parameters:

notification_code and severity are numerical values which correspond to the STREAM_NOTIFY_* constants listed below. If a descriptive message is available from the stream, message and message_code will be populated with the appropriate values. The meaning of these values is dependent on the specific wrapper in use. bytes_transferred and bytes_max will be populated when applicable.

Installation

Streams are an integral part of PHP as of version 4.3.0. No steps are required to enable them.

Stream Classes

User designed wrappers can be registered via stream_wrapper_register(), using the class definition shown on that manual page.

class php_user_filter is predefined and is an abstract baseclass for use with user defined filters. See the manual page for stream_filter_register() for details on implementing user defined filters.

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

Constant Description
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).
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 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 severity level of STREAM_NOTIFY_SEVERITY_ERR.
STREAM_NOTIFY_MIME_TYPE_IS The mime-type of resource has been identified, refer to 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 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 a ICMP socket.
STREAM_IPPROTO_IP + Provides a 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 a 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.
Note:

The constants marked with * are just available since PHP 5.0.0.

Note:

The constants marked with + are available since PHP 5.1.0 and are meant to be used with stream_socket_pair(). Please note that some of these constants might not be available in your system.

Stream Errors

As with any file or socket related function, an operation on a stream may fail for a variety of normal reasons (i.e.: Unable to connect to remote host, file not found, etc...). A stream related call may also fail because the desired stream is not registered on the running system. See the array returned by stream_get_wrappers() for a list of streams supported by your installation of PHP. As with most PHP internal functions if a failure occurs an E_WARNING message will be generated describing the nature of the error.

Examples

Example 2368. Using file_get_contents() to retrieve data from multiple sources

<?php
/* Read local file from /home/bar */
$localfile = file_get_contents("/home/bar/foo.txt");

/* Identical to above, explicitly naming FILE scheme */
$localfile = file_get_contents("file:///home/bar/foo.txt");

/* Read remote file from www.example.com using HTTP */
$httpfile  = file_get_contents("http://www.example.com/foo.txt");

/* Read remote file from www.example.com using HTTPS */
$httpsfile = file_get_contents("https://www.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTP */
$ftpfile   = file_get_contents("ftp://user:pass@ftp.example.com/foo.txt");

/* Read remote file from ftp.example.com using FTPS */
$ftpsfile  = file_get_contents("ftps://user:pass@ftp.example.com/foo.txt");
?>


Example 2369. Making a POST request to an https server

<?php
/* Send POST request to https://secure.example.com/form_action.php
* Include form elements named "foo" and "bar" with dummy values
*/

$sock = fsockopen("ssl://secure.example.com", 443, $errno, $errstr, 30);
if (!
$sock) die("$errstr ($errno)\n");

$data = "foo=" . urlencode("Value for Foo") . "&bar=" . urlencode("Value for Bar");

fwrite($sock, "POST /form_action.php HTTP/1.0\r\n");
fwrite($sock, "Host: secure.example.com\r\n");
fwrite($sock, "Content-type: application/x-www-form-urlencoded\r\n");
fwrite($sock, "Content-length: " . strlen($data) . "\r\n");
fwrite($sock, "Accept: */*\r\n");
fwrite($sock, "\r\n");
fwrite($sock, "$data\r\n");
fwrite($sock, "\r\n");

$headers = "";
while (
$str = trim(fgets($sock, 4096)))
 
$headers .= "$str\n";

echo
"\n";

$body = "";
while (!
feof($sock))
 
$body .= fgets($sock, 4096);

fclose($sock);
?>


Example 2370. Writing data to a compressed file

<?php
/* Create a compressed file containing an arbitrarty string
* File can be read back using compress.zlib stream or just
* decompressed from the command line using 'gzip -d foo-bar.txt.gz'
*/
$fp = fopen("compress.zlib://foo-bar.txt.gz", "wb");
if (!
$fp) die("Unable to create file.");

fwrite($fp, "This is a test.\n");

fclose($fp);
?>


Table of Contents

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 — Create a streams context
stream_context_get_default — Retreive the default streams context
stream_context_get_options — Retrieve options for a stream/wrapper/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_encoding — Set character set for stream encoding
stream_filter_append — Attach a filter to a stream
stream_filter_prepend — Attach a filter to a stream
stream_filter_register — Register a stream filter implemented as a PHP class derived from php_user_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 list of registered filters
stream_get_line — Gets line from stream resource up to a given delimiter
stream_get_meta_data — Retrieves header/meta data from streams/file pointers
stream_get_transports — Retrieve list of registered socket transports
stream_get_wrappers — Retrieve list of registered streams
stream_register_wrapper — Alias of stream_wrapper_register()
stream_resolve_include_path — Determine what file will be opened by calls to fopen() with a relative 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_timeout — Set timeout period on a stream
stream_set_write_buffer — Sets 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_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

Code Examples / Notes » ref.stream

jausions

For the "notification" index of the $params for stream_context_set_params() function, a callable function is accepted. That is array(&$object, 'methodName') will also work.

marcus

As this article says, there is no quoted_printable_encode function() in PHP: http://www.zend.com/manual/filters.convert.php
However there is a stream filter for quoted printable encoding. Here's an example function that produces output suitable for email and doesn't explicitly use external files (though it might do for strings over 2Mb due to the nature of the temp stream type):
<?php
function quoted_printable_encode($string) {
       $fp = fopen('php://temp/', 'r+');
       $params = array('line-length' => 70, 'line-break-chars' => "\r\n");
       stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params);
       fputs($fp, $string);
       rewind($fp);
       return stream_get_contents($fp);
}
echo quoted_printable_encode(str_repeat("hello there ", 50)." a=1\r\n")."\n";
?>
The filter needs to be restricted to STREAM_FILTER_READ because by default it will get filtered both going into and out of the stream, and will thus get encoded twice.
It should be much faster than using a PHP implementation of the same thing, though note that this will only work in PHP 5.1+.


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker