Usage of stream (stream) in PHP

Source: Internet
Author: User
Tags md5 spl php and socket strlen wrapper

 stream is one of the most overlooked function series in PHP development (SPL series, stream series, pack function, encapsulation protocol), but it is a useful and important function. The stream can be translated as "stream", and the following is the use method

In Java, streaming is a very important concept. The concept of   flow (stream) derives from the concept of pipeline (pipe) in Unix. In Unix, pipelines are an uninterrupted stream of bytes used to communicate between programs or processes, or to read and write peripherals, external files, and so on. According to the direction of the flow can be divided into input and output streams, while the other can be set on the periphery of the flow, such as buffer flow, so you can get more flow processing methods.   The flow in PHP and the flow in Java is actually the same concept, just a bit simpler. Because PHP is primarily used for web development, the concept of "streaming" is less mentioned. If you have a Java base, it's easier to understand the flow in PHP. In fact, many of the advanced features in PHP, such as SPL, exceptions, filters, etc. are referenced in the implementation of Java, in the concept and principle of expatiating.   For example, the following is a section of the PHP SPL standard library usage (traversal directory, find fixed conditions of the file):     Code as follows: Class Recursivefilefilteriterator extends Filteriterator {   //Meet the conditional extension     protected $ext = array (' jpg ', ' gif ');      /** &NB Sp    * provides $path and generates the corresponding directory iterator      */    Public function __construct ($path)     {        parent::__construct (new Recursiveiteratoriterator recursivedirectoryiterator ($path) ));    }      /**      * Check file name extensions to meet conditions      */    public F Unction Accept ()     {        $item = $this->getinneriteraTor ();         if ($item->isfile () && In_array (PathInfo ($item->getfilename (), Pathinfo_ EXTENSION), $this->ext))         {            return TRUE;   &N Bsp    }    }}  //instantiated foreach (New Recursivefilefilteriterator (' D:/history ') as $item) {    Echo $item. Php_eol;       Java also has and its expatiating code:   Code as follows: public class Directorycontents {    public static void Ma In (string[] args) throws IOException     {        File f = new File (".");//Current Direct Ory           FilenameFilter textfilter = new FilenameFilter ()         {&nbs P           Public boolean accept (File dir, String name)             {                String lowercasename = Name.tolowercase ();   &NBsp             if (Lowercasename.endswith ("TXT"))             &N Bsp   {                    return true;         &N Bsp      }                 else           &NB Sp     {                    return false;       & nbsp        }             {       };           file[] files = f.listfiles (TextFilter);           for (File file:files)         {        &NBSP ;   if (File.isdirectory ())             {            &NBSP ;   System.out.print ("directory:");            }             else             {                System.out.print ("    file:");                           SYSTEM.OUT.PRINTLN (FILE.GETCA Nonicalpath ());        }    }}       Take this example, on the one hand, PHP and Java in many aspects of the concept is the same, master a language to understand another language will have a great Help; On the other hand, this example also helps us to mention the filter stream-filter below. In fact, is also a design pattern embodiment.   We can take a few examples to understand the use of stream series functions first.   Below is an example of using a socket to crawl data:   Code is as follows: $post _ =array (  ' author ' => ' Gonn ',   ' mail ' => ' gonn@nowamagic . Net ',   ' url ' => ' http://www.nowamagic.net/',   ' text ' => ' welcomes access to concise modern Magic ');   $data =http_build_query ($post _); $fp = Fsockopen ("Nowamagic.net", $errno, $errstr, 5);   $out = "POST http://nowamagic.net/news/1/comment http/1.1rn"; $out. = "HOST:TYPECHO.ORGRN"; $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 "." RN "; $out. = "CONTENT-TYPE:APPLICATION/X-WWW-FORM-URLENCODEDRN"; $out. = "Phpsessid=082b0cc33cc7e6df1f87502c456c3eb0rn"; $out. = "Content-length:". Strlen ($data). "RN"; $out. = "Connection:closernrn"; $out. = $data. " Rnrn ";   Fwrite ($fp, $out); while (!feof ($fp)) {    echo fgets ($FP, 1280);}   fclose ($FP);       We can also use Stream_socket implementation, which is very simple, just open the socket code to replace the following:     code as follows: $fp = Stream_socket_client (" Tcp://nowamagic.net:80 ", $errno, $errstr, 3);     To see an example of a stream:   file_get_contents function is commonly used to read the contents of the file, but this function can also be used to crawl remote URLs, play a similar role with curl.     Code as follows: $opts = array (  ' http ' =>array (    ' method ' => ' POST ',     ' header ' =&gt ; "Content-type:application/x-www-form-urlencodedrn".       "Content-length:". Strlen ($data). "RN",     ' content ' => $data));   $context = stream_context_create ($opts); File_get_conTents (' http://www.jb51.net/news ', false, $context);       Note the third parameter, $context, which is the HTTP streaming context, can be understood as a pipe that is nested on the file_get_contents function. Similarly, we can also create an FTP stream, a socket stream, and put it in the corresponding function.   More about stream_context_create, you can refer to: PHP function Completion: stream_context_create () simulation post/get. The functions of the two stream series mentioned above are all similar to the wrapper flow, which acts on the input/output stream of some protocol. This usage and concept, in fact, and Java in the flow is not a big difference, such as Java often have such a way:     Code as follows: New DataOutputStream (New Bufferedoutputstream FileOutputStream (New File (FileName)));     A laminar flow embedded in another laminar flow, and PHP is similar to the wonderful.   Let's take another look at the role of the filter Flow:   Code as follows: $fp = fopen (' c:/test.txt ', ' w+ ');  /* ROT13 filter function on the write stream/Stream_filter_append ($fp, "string.rot13", stream_filter_write);  /* Write data after ROT13 filter processing * * fwrite ($FP, "This is a testn"); Rewind ($FP);  /* Read the written data, unique nature is the processed characters of the * * FPASSTHRU ($FP); Fclose ($FP);  //OUTPUT:GUVF VF n grfg       In the above example, if we set the type of filter to Stream_filter_all, that is, the same effect on the read-write stream, Then the data read and write will be processed by the ROT13 filter, and the data we read is consistent with the original data written.   You may be surprised that the "string.rot13" Change in Stream_filter_appendThe amount of inexplicable, this is actually a built-in PHP filter.   Use the following method to print out the PHP built-in flow:   Code as follows: Streamlist = Stream_get_filters (); Print_r ($streamlist);     Output:     Code as follows: Array (    [0] => convert.iconv.*     [1] => mcrypt.* &nbs P   [2] => mdecrypt.*     [3] => string.rot13     [4] => string.toupper     [5] => string.tolower     [6] => string.strip_tags     [7] => convert.*     [8] => C onsumed     [9] => dechunk     [a] => zlib.*     [one] => bzip2.*)     from However, we think of defining our own filters, which is not difficult: The   code is as follows: Class Md5_filter extends Php_user_filter {    function filter ($in, $out, & $consumed, $closing)     {        while ($bucket = stream_bucket_make_writeable ($in))         {            $bucket->data = MD5 ($bucket->data);   & nbsp         $consumed + + $bucket->datalen;             Stream_bucket_append ($out, $bucket);        }          //Data processing successful, available for other channels to read         return PSFS _pass_on;    }} stream_filter_register ("String.md5", "Md5_filter");       NOTE: Filter name can be taken at random. After  , we can use the "string.md5" as our custom filter.   This filter is a bit confusing to look at, in fact we just need to look at the structure of the Php_user_filter class and the built-in method to understand.   Filter flow is the most suitable to do is the file format conversion, including compression, coding and decoding, in addition to these "partial door" usage, the filter flow is more useful in the debugging and logging functions, such as in the socket development, register a filter stream for log records. For example, the following example:     code is as follows: Class Md5_filter extends Php_user_filter {    public function filter ($in, $out, &am p; $consumed, $closing)     {        $data = ""         while ($bucket = Stream_bucket_make_writeable ($in))         {            $bucket->dat A = MD5 ($bucket->data);             $consumed + + $bucket->datalen;             Stream_bucket_append ($out, $bucket);        }           Call_user_func ($this->params, $data);         return psfs_pass_on;    }}   $callback = function ($data) {    file_put_contents ("C:log.txt", Date ("Y-m-d h:i"). " RN "); };       This filter can not only handle the input stream, but also callback a function for logging.   can be used in this way:     Code as follows: Stream_filter_prepend ($fp, "String.md5", Stream_filter_write, $callback);     PHP Stream stream series function also has a very important flow, is the wrapper class stream streamwrapper. Using wrapper flows enables different types of protocols to manipulate data using the same interface.  

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.