PHP Stream Stream Concepts and usage

Source: Internet
Author: User

Reprinted from http://www.nowamagic.net/librarys/veda/detail/2587

<?PHPclassRecursivefilefilteriteratorextendsfilteriterator{//the extension that satisfies the condition    protected $ext=Array(' jpg ', ' gif '); /** * Provide $path and generate the corresponding directory iterator*/     public function__construct ($path) {parent:: __construct (NewRecursiveiteratoriterator (NewRecursivedirectoryiterator ($path))); }    /** * Check if the file name extension meets the criteria*/     public functionAccept () {$item=$this-Getinneriterator (); if($item->isfile () &&In_array(PathInfo($item->getfilename (), pathinfo_extension),$this-Ext)) {            return TRUE; }    }}//instantiation offoreach(NewRecursivefilefilteriterator (' d:/history ') as $item){    Echo $item.Php_eol;}


Java also has code for its expatiating:

 public classdirectorycontents{ public Static voidMain (string[] Args)throwsIOException {File F=NewFile (".");//current DirectoryFilenameFilter TextFilter=Newfilenamefilter () { public BooleanAccept (File dir, string Name) {string lowercasename=Name.tolowercase (); if(lowercasename.endswith (". txt"))                {                    return true; }                Else                {                    return false;        }            }        }; file[] Files=F.listfiles (textfilter);  for(File file:files) {if(file.isdirectory ()) {System.out.print ("directory:"); }            Else{System.out.print ("file:");        } System.out.println (file.getcanonicalpath ()); }    }}
This example shows that PHP and Java have the same concept in many aspects, that mastering one language can be very helpful in understanding another language, and this example also helps us to refer to the filter flow-filter BELOW. In fact, It is also a design pattern Embodiment.

We can start with a few examples to understand the use of stream series Functions.

Here is an example of using a socket to fetch data:

<?PHP$post _=Array (    ' Author ' = ' gonn ', ' mail ' = ' [email protected] ', ' url ' = ' http://www.nowamagic.net/', ' text ' and ' = ' Welcome to the concise now Generation Magic ');$data=Http_build_query($post _);$fp=Fsockopen("nowamagic.net", 80,$errno,$errstr, 5);$out= "POST Http://nowamagic.net/news/1/comment http/1.1\r\n";$out. = "host:typecho.org\r\n";$out. = "user-agent:mozilla/5.0 (Windows; U Windows NT 6.1; zh-cn; Rv:1.9.2.13) gecko/20101203 firefox/3.6.13 "." \ r \ n ";$out. = "content-type:application/x-www-form-urlencoded\r\n";$out. = "phpsessid=082b0cc33cc7e6df1f87502c456c3eb0\r\n";$out. = "content-length:".strlen($data) . "\ r \ n";$out. = "connection:close\r\n\r\n";$out.=$data." \r\n\r\n ";fwrite($fp,$out); while(!feof($fp)){    Echo fgets($fp, 1280);}fclose($fp);

can also be implemented with stream_socket, this is very simple, just need to open the socket code to replace the Following:

$fp stream_socket_client $errno $errstr, 3);

The File_get_contents function is commonly used to read the contents of a file, but this function can also be used to crawl remote urls, playing a similar role as Curl.

  $opts  = array   ( ' http ' =>array   ( ' method ' = ' POST ', ' header ' =" content-type:application/x-www-form-urlencoded\r\n "). "content-length:". strlen  ( $data ). "\ r \ n", ' content ' =  $data    $context  = stream_context_create  ( $opts   file_get_contents  (' http://nowamagic.net/news/1/comment ', false ,  $context ); 

Note the third argument, $context, the HTTP stream context, can be understood as a pipe set on the file_get_contents Function. similarly, We can also create an FTP stream, a socket stream, and set it in the corresponding Function.

More about stream_context_create, you can refer to: php function completion: stream_context_create () simulation Post/get.

The function of the two stream series mentioned above is a wrapper-like flow that acts on the input and output stream of some kind of protocol. Such use and concept, in fact, and Java in the flow is not a big difference, such as Java often have such a way of writing:

Newdataoutputstream (newbufferedoutputstream (newfileoutputstream (newFile (fileName)));

A laminar layer is nested in another laminar flow, and PHP is similar to the Wonderful. Let's look at the effect of a filter flow:

$fp=fopen(' c:/test.txt ', ' w+ ');/*the ROT13 Filter acts on the write stream*/Stream_filter_append($fp, "string.rot13",stream_filter_write);/*The data written is processed by the ROT13 filter*/fwrite($fp, "this is a test\n");Rewind($fp);/*read the written data, the original nature is the processed characters*/Fpassthru($fp);fclose($fp);//OUTPUT:GUVF VF N GRFG

In the above example, if we set the type of the filter to stream_filter_all, that is, at the same time on the Read-write stream, the Read-write data will be processed by the ROT13 filter, and the data we read is consistent with the original data being Written.

You may be surprised by the stream_filter_append of the "string.rot13" variable, which is actually a filter built into PHP.

Use the following method to print out the PHP built-in Flow:

$streamlist stream_get_filters (); Print_r ($streamlist)

naturally, we will think of defining our own filters, which is not difficult:

classMd5_filterextends Php_user_filter{    functionFilter$in,$out, &$consumed,$closing)    {         while($bucket=stream_bucket_make_writeable($in))        {            $bucket->data =MD5($bucket-data); $consumed+=$bucket-datalen; Stream_bucket_append($out,$bucket); }        //data processing is successful and can be read by other pipelines        returnpsfs_pass_on; }}Stream_filter_register("string.md5", "md5_filter");

Note: the filter name can be arbitrarily Taken.

You can then use the "string.md5" as our custom filter.

The way the filter is written seems to be a bit confusing, in fact we just need to look at the structure of the Php_user_filter class and the built-in approach to understanding it.

Filter flow is the most suitable to do is the file format conversion, including compression, codec, In addition to these "partial gate" usage, the filter stream is more useful in debugging and logging functions, such as in the socket development, register a filter stream to log records. For example, the Following:

 classMd5_filterextends Php_user_filter{     public functionFilter$in,$out, &$consumed,$closing)    {        $data="";  while($bucket=stream_bucket_make_writeable($in))        {            $bucket->data =MD5($bucket-data); $consumed+=$bucket-datalen; Stream_bucket_append($out,$bucket); }        Call_user_func($this->params,$data); returnpsfs_pass_on; }}$callback=function($data){    file_put_contents("c:\log.txt",Date("y-m-d h:i"). " \ r \ n ");};

This filter can not only process the input stream, but also callback a function for Logging. You can use This:

Stream_filter_prepend ($fp, "string.md5", stream_filter_write,$callback);

There is also a very important stream in the Stream series function in php, which is the wrapper class flow Streamwrapper. Using wrapper flow allows different types of protocols to manipulate data using the same interface.

PHP Stream Stream Concepts and usage

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.