Home  >  Article  >  Backend Development  >  Usage of stream in php_PHP tutorial

Usage of stream in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:35:13772browse

In Java, stream is a very important concept.

The concept of stream originates from the concept of pipe in UNIX. In UNIX, a pipe is an uninterrupted byte stream, used to implement communication between programs or processes, or to read and write peripheral devices, external files, etc. According to the direction of the stream, it can be divided into input stream and output stream. At the same time, other streams can be placed around it, such as buffer stream, so that more stream processing methods can be obtained.

Streams in PHP and streams in Java are actually the same concept, just a little simpler. Since PHP is mainly used for web development, the concept of "flow" is rarely mentioned. If you have a Java foundation, it will be easier to understand streams in PHP. In fact, many advanced features in PHP, such as SPL, exceptions, filters, etc., all refer to the implementation of Java and have the same concepts and principles.

For example, the following is a usage of the PHP SPL standard library (traverse the directory and find files with fixed conditions):

Copy code The code is as follows:

class RecursiveFileFilterIterator extends FilterIterator
{
// Extensions that meet the conditions
protected $ext = array('jpg','gif');

/**
* Provide $path and generate the corresponding directory iterator
*/
public function __construct($path)
{
parent::__construct(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
}

/**
* Check whether the file extension meets the conditions
*/
public function accept()
{
$item = $this->getInnerIterator();
if ($item->isFile( ) && in_array(pathinfo($item->getFilename(), PATHINFO_EXTENSION), $this->ext))
                                                                 >
// Instantiate
foreach (new RecursiveFileFilterIterator('D:/history') as $item)
{
echo $item . PHP_EOL;

}




There is also the same code in Java:

Copy code

The code is as follows:


public class DirectoryContents
{
    public static void main(String[] args) throws IOException
    {
        File f = new File("."); // current directory

        FilenameFilter textFilter = new FilenameFilter()
        {
            public boolean accept(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());
        }
    }
}

举这个例子,一方面是说明PHP和Java在很多方面的概念是一样的,掌握一种语言对理解另外一门语言会有很大的帮助;另一方面,这个例子也有助于我们下面要提到的过滤器流-filter。其实也是一种设计模式的体现。

我们可以通过几个例子先来了解stream系列函数的使用。

下面是一个使用socket来抓取数据的例子:

复制代码 代码如下:

$post_ =array (
 'author' => 'Gonn',
 'mail'=>'gonn@nowamagic.net',
 'url'=>'http://www.nowamagic.net/',
 'text'=>'欢迎访问简明现代魔法');

$data=http_build_query($post_);
$fp = fsockopen("nowamagic.net", 80, $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);

我们也可以用stream_socket 实现,这很简单,只需要打开socket的代码换成下面的即可:

复制代码 代码如下:

$fp = stream_socket_client("tcp://nowamagic.net:80", $errno, $errstr, 3);

Let’s look at another example of stream:

The file_get_contents function is generally used to read file contents, but this function can also be used to grab remote URLs, playing a similar role to curl.

Copy code The code is as follows:

$opts = array (
'http'=>array(
'method' => 'POST',
'header'=> "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 that the third parameter, $context, is the HTTP stream context, which can be understood as a pipe attached to the file_get_contents function. In the same way, we can also create FTP streams and socket streams and set them in the corresponding functions.

For more information about stream_context_create, please refer to: PHP function completion: stream_context_create() simulates POST/GET.

The two stream series functions mentioned above are wrapper-like streams that act on the input and output streams of a certain protocol. This kind of usage and concept is actually not much different from streams in Java. For example, Java often writes like this:

Copy code The code is as follows:

new DataOutputStream(new BufferedOutputStream(new FileOutputStream(new File(fileName)))));

One layer of flow is nested within another layer of flow, which is similar to that in PHP.

Let’s look at the function of the filter stream:

Copy code The code is as follows:

$fp = fopen('c:/test.txt', 'w+') ;

/* Apply the rot13 filter to the write stream */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* The written data is processed by the rot13 filter*/
fwrite($fp, "This is a testn");
rewind($fp);

/* Read and write data, the uniqueness is naturally the processed characters */
fpassthru($fp);
fclose($fp);

// output: Guvf vf n grfg

In the above example, if we set the filter type to STREAM_FILTER_ALL, which acts on the read and write streams at the same time, then the read and write data will be processed by the rot13 filter, and the data we read will be the same as the data we wrote. The original data entered is consistent.

You may be surprised that the variable "string.rot13" in stream_filter_append comes from nowhere. This is actually a filter built into PHP.

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

Copy code The code is as follows:

streamlist = stream_get_filters();
print_r($streamlist);

Output:

Copy code The code is as follows:

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
[10] => zlib.*
[11] => bzip2.*
)

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

Copy code 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);
$consumed += $bucket->datalen;
stream_bucket_append($out, $bucket) ;
}

                                                                                                              use   with use using             use using ’ ’ ’ s ’ through ’ s ’ through ’s ’ through ‐ to ‐ ‐‐‐ return PSFS_PASS_ON;
​ }
}
stream_filter_register("string.md5", "md5_filter");

Note: The filter name can be chosen as desired.

After that, you can use our custom filter "string.md5".

The way this filter is written seems a bit confusing. In fact, we only need to look at the structure and built-in methods of the php_user_filter class to understand.

The most suitable thing for the filter stream is file format conversion, including compression, encoding and decoding, etc. In addition to these "deviant" usages, one of the more useful aspects of the filter stream is debugging and logging functions, such as in socket During development, register a filter stream for log recording. For example, the following example:

Copy code The code is as follows:
class md5_filter extends php_user_filter
{
public function filter($in, $out, &$consumed, $closing)
{
$data="";
while ($bucket = stream_bucket_make_writeable($in))
{
$bucket->data = md5($bucket->data);
                    $consumed += $bucket->datalen;
Call_user_func ($ this-& gt; 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 process the input stream, but also callback a function for logging.

can be used like this:

Copy code

The code is as follows:stream_filter_prepend($fp, "string.md5", STREAM_FILTER_WRITE,$callback);

There is also a very important stream in the stream series functions in PHP, which is the wrapper class stream streamWrapper. Using wrapper streams allows different types of protocols to use the same interface to manipulate data.

http://www.bkjia.com/PHPjc/745822.html

www.bkjia.com

http: //www.bkjia.com/PHPjc/745822.htmlTechArticleIn Java, stream is a very important concept. The concept of stream originates from the concept of pipe in UNIX. In UNIX, a pipe is an uninterrupted stream of bytes used to implement a program or process...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn