Home Backend Development PHP Tutorial Usage of stream in php_PHP tutorial

Usage of stream in php_PHP tutorial

Jul 13, 2016 am 10:35 AM
php stream

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles