PHP Streams (streaming) detailed introduction and use of _php examples

Source: Internet
Author: User
Tags php class prepare readfile what php wrapper

PHP streams is a built-in core operation, probably rarely used by ordinary developers, it is used for unified file, network, data compression and other types of file operations, and for these types of file operations to provide a common set of functional interfaces.

A stream is a resource object with a streaming behavior, and each stream object has a wrapper class. The Stream can be referenced by way of <scheme>://<target>. Where <scheme> is the name of the wrapper class the contents of the,<target> are specified by the syntax of the wrapper class, and the syntax of the different wrapper classes varies.
Look at the built-in wrapper classes that PHP defaults to:

Print_r (Stream_get_wrappers ());
/* Array
(
  [0] => php
  [1] => file
  [2] => glob
  [3] => data
  [4] => http
  [5] => FTP
  [6] => zip
  [7] => compress.zlib
  [8] => HTTPS
  [9] => FTPs
  [a] => phar
   )
* * *

Check out the PHP manual for the Protocol and wrapper classes supported by PHP.
Look at the following section of code that uses file_get_contents () to get the data:

* 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.c Om/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.examp Le.com/foo.txt ");
 
 /* Read remote file from ftp.example.com using FTPS
 *  /$ftpsfile = file_get_contents ("Ftps://user:pass@ftp.ex Ample.com/foo.txt ");

In fact ReadFile ('/path/to/somefile.txt ') or ReadFile (' file:///path/to/somefile.txt '), these two methods are equivalent. Because the default wrapper class for PHP is file://.

It is clear from the manual that you can register your own wrapper through Stream_register_wrapper () to see the examples in the manual.
OK, here's a brief introduction to a php://, which is the wrapper class that PHP uses to process IO streams (click here for an example). More powerful input and output streams can be accessed through php://:

Php://stdin: accesses the corresponding input stream for the PHP process, such as keyboard input when getting the CLI to execute the script.
Php://stdout: accesses the corresponding output stream of the PHP process.
Php://stderr: accesses the corresponding error output of the PHP process.
Php://input: A read-only stream that accesses the raw data of the request.
Php://output: Write-only data stream, written to the output area in the same way as print and echo.
PHP://FD: Allows direct access to the specified file descriptor. Example PHP://FD/3 references a file descriptor of 3.
Php://memory: Allows temporary data to be read and written. Store the data in memory.
Php://temp: IBID., will be stored in the temporary file after the amount of memory reaches a predefined limit (2MB by default).
Php://filter: Filter.

PHP can also modify and enhance the wrapper class through the context and filter.
(1) About the context, such as PHP through Stream_context_create () to set the time to get the file timeout, this code must be used:

$opts = Array ('
  http ' =>array (
    ' method ' => ' get ',
    ' timeout ' =>60,
  )
);
$context = Stream_context_create ($opts);
$html =file_get_contents (' http://www.jb51.net ', false, $context);

(2) With regard to filter filters, first look at what PHP has built-in filters:

Print_r (Stream_get_filters ());
/* Array
(
  [0] => convert.iconv.*
  [1] => mcrypt.*
  [2] => mdecrypt.*
  [3] => STRING.ROT13
  [4] => string.toupper
  [5] => string.tolower
  [6] => string.strip_tags
  [7] = > convert.*
  [8] => consumed
  [9] => dechunk
  [a] => zlib.*
)
* *

Custom filters can be created by Stream_filter_register () and the built-in Php_user_filter, as follows:

* Define Our Filter class *
/Class Strtoupper_filter extends Php_user_filter {
  function filter ($in, $out, &am P $consumed, $closing)
  {while
    ($bucket = stream_bucket_make_writeable ($in)) {
      $bucket-> data = Strtou Pper ($bucket-> data);
      $consumed + + $bucket-> datalen;
      Stream_bucket_append ($out, $bucket);
    }
    Return psfs_pass_on
  }
}
 
/* Register We filter with PHP/
stream_filter_register ("Strtoupper", "Strtoupper_filter")
or Die ("Failed To register Filter ");
 
$fp = fopen ("Foo-bar.txt", "w");
 
/* Attach The registered filter to the stream just opened
/stream_filter_append ($fp, "Strtoupper");
 
Fwrite ($fp, "line1\n");
Fwrite ($fp, "word-2\n");
Fwrite ($FP, "easy as 123\n");
 
Fclose ($FP);
 
 
ReadFile ("Foo-bar.txt");
/* Results are as follows:
LINE1 WORD-2 Easy as
123
* *

Provide a list of streams functions in PHP as follows:

Stream_bucket_append function: Add data to the queue Stream_bucket_make_writeable function: Returns a data object Stream_bucket_new function from the operation's queue: Create a new data for the current queue Stream_bucket_prepend function: Prepare data to queue Stream_context_create function: Create a data Flow context Stream_context_get_default function: Get the default data flow context Stream_ Context_get_options function: Gets the settings of the data stream Stream_context_set_option function: Set the Stream_context_set_params function for data flow, packet, or context: for data flow, Packet or context set parameter Stream_copy_to_stream function: Copying between data streams Stream_filter_append function: Adding filters for Data flow Stream_filter_ prepend function: Prepare add filter stream_filter_register function for data flow: Registers a filter for a data stream and executes the Stream_filter_remove function as a PHP class: Removing filters from a data stream STREAM_ get_contents function: Reads the remaining data in the data stream to the string Stream_get_filters function: Returns the registered Data Flow filter List Stream_get_line function: Gets rows from the data flow resource according to the given delimiter STREAM_
Get_meta_data function: Get header/metadata Stream_get_transports function from encapsulated protocol file pointer: Returns the registered socket transfer List Stream_get_wrappers function: Returns a list of registered streams Stream_register_wrapper function: Registers a URL encapsulation protocol Stream_select function implemented with the PHP class: receives an array of data streams and waits for their state to change stream_set_ Blocking function: Set a data stream to a blocking or non-blocking state stream_set_timeout function: Timeout setting for Data flow Stream_set_write_buffer function: Set buffer for data flow stream_socket_ Accept function: Accept by function Stream_ Socket_seSocket connection Stream_socket_client function created by RVer (): Open a network or socket connection for a UNIX host Stream_socket_enable_ Crypto function: Turn on or off the data encryption Stream_socket_get_name function for an already connected socket: Gets the name of the local or network socket stream_socket_ Pair function: Create two no difference socket stream connection Stream_socket_recvfrom function: Get data from socket, regardless of its connection stream_socket_sendto function: Send data to socket Whether it's connected or not Stream_socket_server function: Create a network or UNIX socket service-side Stream_wrapper_restore function: Restore a previously logged out packet Stream_wrapper_
 Unregister function: Unregister a URL address package

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.