Understand the Streams in PHP

Source: Internet
Author: User
Tags readfile

Streams is a powerful tool that PHP provides, and we often inadvertently use it, and if good use will greatly improve PHP productivity. When you harness the power of streams, your application will ascend to a new height.

The following is a description of streams in the PHP manual:

Streams was introduced in PHP 4.3.0, which is used to manipulate the file, network, data compression and other class files, providing a common set of function interfaces for these class file operations. In short, a stream is a resource object with streaming behavior. In other words, we can read and write the stream in a linear fashion. And you can use Fseek () to jump to any location within the stream.

Each streams object has a wrapper class that can add related code that handles special protocols and encodings in the wrapper. There are some commonly used wrapper classes built into PHP, and we can create and register custom wrapper classes. We can even use the existing context and filter to modify and enhance the wrapper class.

Stream Basics

Stream can be referenced by <scheme>://<target>. Where <scheme> is the name of the wrapper class,<target> content is specified by the syntax of the wrapper class, the syntax of the different wrapper classes will vary.

The default wrapper class for PHP is file://, which means that when we access the file system, we are actually using a stream. We can read the contents of the file in the following two ways, ReadFile ('/path/to/somefile.txt ') or ReadFile (' File:///path/to/somefile.txt '), both of which are equivalent. If you are using ReadFile (' http://google.com/'), then PHP will choose the HTTP stream wrapper class to operate.

As mentioned above, PHP provides a number of built-in package-to-class, protocol, and filter. You can query the wrapper classes supported by this machine as described below:

1234 <?phpprint_r(stream_get_transports());print_r(stream_get_wrappers());print_r(stream_get_filters());

The output on my machine is:

1234567891011121314151617181920212223242526272829303132333435363738394041 Array(    [0] => tcp    [1] => udp    [2] => unix    [3] => udg    [4] => ssl    [5] => sslv3    [6] => sslv2    [7] => tls)Array(    [0] => https    [1] => ftps    [2] => compress.zlib    [3] => compress.bzip2    [4] => php    [5] => file    [6] => glob    [7] => data    [8] => http    [9] => ftp    [10] => zip    [11] => phar)Array(    [0] => zlib.*    [1] => bzip2.*    [2] => convert.iconv.*    [3] => string.rot13    [4] => string.toupper    [5] => string.tolower    [6] => string.strip_tags    [7] => convert.*    [8] => consumed    [9] => dechunk    [10] => mcrypt.*    [11] => mdecrypt.*)

There are a lot of features that look good, right?

In addition to the above built-in stream, we can also write more third-party streams for Amazon S3, MS Excel, Google Storage, Dropbox and even Twitter.

PHP://Packing Class

In PHP, the wrapper class for processing I/O stream is built into this language. Can be divided into several categories, based on Php://stdin,php://stdout, and Php://stderr, which are 3 streams mapped to the default I/O resources. PHP also provides php://input, through which the wrapper class can access the raw body in a POST request in a read-only manner. This is a very useful feature, especially when dealing with remote services that embed data payloads in a POST request.

Let's use the Curl tool to do a simple test:

1 curl -d "Hello World"-d "foo=bar&#038;name=John"<a href="http://localhost/dev/streams/php_input.php">http://localhost/dev/streams/php_input.php</a>

The test results for using Print_r ($_post) in PHP scripts are as follows:

12345 Array(    [foo] => bar    [name] => John)

We note that the $_post array is inaccessible to the first item of data. But if we use ReadFile (' Php://input '), the result will be different:

1 Hello World&#038;foo=bar&#038;name=John

PHP 5.1 adds php://memory and Php://tempstream, which are used to read and write temporary data. As implied in the wrapper class naming, this data is stored in memory or temporary files in the underlying system.

Php://filter is a meta wrapper class that is used to add the filter function to the stream. Filter is enabled when the stream is opened using ReadFile () or file_get_contents ()/stream_get_contents (). Here is an example:

123456 <?php// Write encoded datafile_put_contents("php://filter/write=string.rot13/resource=file:///path/to/somefile.txt","Hello World");// Read data and encode/decodereadfile("php://filter/read=string.toupper|string.rot13/resource=http://www.google.com");

In the first example, a filter is used to encode the data saved to disk, and in two cases, two cascading filter is used to read the data from the remote URL. Using filter can bring the most powerful features to your application.

Stream context

The context is a set of stream-related parameters or options that you can use to modify or enhance the behavior of the wrapper class. For example, using context to modify the HTTP wrapper is a common usage scenario. This allows us to do some simple network operations without using the Curl tool. Here is an example:

123456789101112 <?php$optsarray(  ‘http‘=>array(    ‘method‘=>"POST",    ‘header‘=> "Auth: SecretAuthTokenrn".        "Content-type: application/x-www-form-urlencodedrn".              "Content-length: "strlen("Hello World"),    ‘content‘=> ‘Hello World‘  ));$default= stream_context_get_default($opts);readfile(‘http://localhost/dev/streams/php_input.php‘);

The first thing to define is an options array, which is a two-bit array that can access the parameters in the form of $array[' wrapper ' [' option_name ']. (Note that the options for the context in each wrapper class are different). Then call Stream_context_get_default () to set these Option,stream_context_get_default () and return the default context as a result. After the setup is complete, the next call to ReadFile () will apply the context you just set up to crawl the content.

In the example above, the content is embedded in the request body so that the remote script can use Php://input to read the content. At the same time, we can use Apache_request_headers () to get the header of the request as follows:

1234567 Array(    [Host] => localhost    [Auth] => SecretAuthToken    [Content-type] => application/x-www-form-urlencoded    [Content-length] => 11)

In the example above, the parameters of the default context are modified, and of course we can create a new context for alternate use.

123 <?php$alternative= stream_context_create($other_opts);readfile(‘http://localhost/dev/streams/php_input.php‘, false, $alternative);
Conclusion

How do we harness the power of stream in the real world? What practical benefits does using stream bring to our programs? As described earlier, stream abstracts all filesystem-related functionality, so my first scenario was to use the wrapper classes of the virtual file system to access the services provided by the PAAs vendors, such as access to Heroku or APPFOG, which actually did not have a real file system. With stream you can port it to the cloud as long as you make a slight change to our application. Next--In my next article--I'll show you how to write a custom wrapper class to implement operations on special file formats and encoding formats.

Understand the Streams in PHP

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.