search
HomeBackend DevelopmentPHP TutorialDetailed introduction and use of PHP Streams (stream)_PHP tutorial

Detailed introduction and use of PHP Streams (stream)

This article mainly introduces the detailed introduction and use of PHP Streams (stream). PHP Streams is a built-in core operation, which may be general It is rarely used by developers. It is used to unify file, network, data compression and other file-like operations, and provides a set of common function interfaces for these file-like operations. Friends who need it can refer to it

PHP Streams is a built-in core operation that may be rarely used by ordinary developers. It is used to unify file, network, data compression and other file-like operations, and provides a set of common function interfaces for these file-like operations.

A stream is a resource object with streaming behavior. Each stream object has a wrapper class. Stream can be referenced via ://. Among them, is the name of the packaging class, and the content in is specified by the syntax of the packaging class. The syntax of different packaging classes will be different.

Let’s take a look at the built-in packaging classes that PHP has by default:

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

print_r(stream_get_wrappers());

/*

Array

(

[0] => php

[1] => file

[2] => glob

[3] => data

[4] => http

[5] => ftp

[6] => zip

[7] => compress.zlib

[8] => https

[9] => ftps

[10] => phar

)

*/

1

2

3

4

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

/* Read local file from /home/bar */

$localfile = file_get_contents ( "/home/bar/foo.txt" );

 

/* Identical to above, explicitly naming FILE scheme */

$localfile = file_get_contents ( "file:///home/bar/foo.txt" );

 

/* Read remote file from www.example.com using HTTP */

$httpfile = file_get_contents ( "http://www.example.com/foo.txt" );

 

/* Read remote file from www.example.com using HTTPS */

$httpsfile = file_get_contents ( "https://www.example.com/foo.txt" );

 

/* Read remote file from ftp.example.com using FTP */

$ftpfile = file_get_contents ( "ftp://user:pass@ftp.example.com/foo.txt" );

 

/* Read remote file from ftp.example.com using FTPS */

$ftpsfile = file_get_contents ( "ftps://user:pass@ftp.example.com/foo.txt" );

5 6 7 8 9 10 11 12 13 14 15 16 17
print_r(stream_get_wrappers()); /* Array ( [0] => php [1] => file [2] => glob [3] => data [4] => http [5] => ftp [6] => zip [7] => compress.zlib [8] => https [9] => ftps [10] => phar ) */
Take a look at the PHP manual for protocols and wrapper classes supported by PHP. Look at the following code that uses file_get_contents() to obtain data:  ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 /* Read local file from /home/bar */ $localfile = file_get_contents ( "/home/bar/foo.txt" ); /* Identical to above, explicitly naming FILE scheme */ $localfile = file_get_contents ( "file:///home/bar/foo.txt" ); /* Read remote file from www.example.com using HTTP */ $httpfile = file_get_contents ( "http://www.example.com/foo.txt" ); /* Read remote file from www.example.com using HTTPS */ $httpsfile = file_get_contents ( "https://www.example.com/foo.txt" ); /* Read remote file from ftp.example.com using FTP */ $ftpfile = file_get_contents ( "ftp://user:pass@ftp.example.com/foo.txt" ); /* Read remote file from ftp.example.com using FTPS */ $ftpsfile = file_get_contents ( "ftps://user:pass@ftp.example.com/foo.txt" );

Actually readfile('/path/to/somefile.txt') or readfile('file:///path/to/somefile.txt'), these two methods are equivalent. Because PHP's default packaging class is file://.

The manual clearly states that you can register your own wrapper through stream_register_wrapper(). You can check out the examples in the manual.

OK, here is a brief introduction to PHP://, which is a wrapper class used by PHP to handle IO streams (click here to see an example). More powerful input and output streams can be accessed via PHP://:

 php://stdin: Access the corresponding input stream of the PHP process, such as used to obtain keyboard input when cli executes a script.

 php://stdout: access the corresponding output stream of the PHP process.

 php://stderr: access the corresponding error output of the PHP process.

php://input: A read-only stream that accesses the requested raw data.

 php://output: a write-only data stream, written to the output area in the same way as print and echo.

 php://fd: allows direct access to the specified file descriptor. Example php://fd/3 refers to file descriptor 3.

 php://memory: allows reading and writing temporary data. Store data in memory.

 php://temp: Same as above, it will be stored in a temporary file after the amount of memory reaches the predefined limit (default is 2MB).

 php://filter: filter.

PHP can also modify and enhance packaging classes through context and filter.

(1) Regarding context, for example, PHP uses stream_context_create() to set the timeout for obtaining files. You must have used this code:

 ?

1

2

3

4

5

6

7

8

$opts = array(

'http'=>array(

'method'=>"GET",

'timeout'=>60,

)

);

$context = stream_context_create($opts);

$html =file_get_contents('http://www.jb51.net', false, $context);

1

2

3

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

print_r(stream_get_filters());

/*

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.*

)

*/

4 5 6 7 8
$opts = array( 'http'=>array( 'method'=>"GET", 'timeout'=>60, ) ); $context = stream_context_create($opts); $html =file_get_contents('http://www.jb51.net', false, $context);
(2) Regarding the filter filter, first let’s take a look at the built-in filters in PHP:  ?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 print_r(stream_get_filters()); /* 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.* ) */

Custom filters can be created through stream_filter_register() and the built-in php_user_filter, as follows:

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

/* Define our filter class */

class strtoupper_filter extends php_user_filter {

function filter ( $in , $out , & $consumed , $closing )

{

while ( $bucket = stream_bucket_make_writeable ( $in )) {

$bucket -> data = strtoupper ( $bucket -> data );

$consumed = $bucket -> datalen ;

stream_bucket_append ( $out , $bucket );

}

return PSFS_PASS_ON ;

}

}

 

/* Register our filter with PHP */

stream_filter_register ( "strtoupper" , "strtoupper_filter" )

or die( "Failed to register filter" );

 

$fp = fopen ( "foo-bar.txt" , "w" );

 

/* Attach the registered filter to the stream just opened */

stream_filter_append ( $fp , "strtoupper" );

 

fwrite ( $fp , "Line1n" );

fwrite ( $fp , "Word - 2n" );

fwrite ( $fp , "Easy As 123n" );

 

fclose ( $fp );

 

 

readfile ( "foo-bar.txt" );

/*

结果如下:

LINE1

WORD - 2

EASY AS 123

*/

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
/* Define our filter class */ class strtoupper_filter extends php_user_filter { function filter ( $in , $out , & $consumed , $closing ) { while ( $bucket = stream_bucket_make_writeable ( $in )) { $bucket -> data = strtoupper ( $bucket -> data ); $consumed = $bucket -> datalen ; stream_bucket_append ( $out , $bucket ); } return PSFS_PASS_ON ; } } /* Register our filter with PHP */ stream_filter_register ( "strtoupper" , "strtoupper_filter" ) or die( "Failed to register filter" ); $fp = fopen ( "foo-bar.txt" , "w" ); /* Attach the registered filter to the stream just opened */ stream_filter_append ( $fp , "strtoupper" ); fwrite ( $fp , "Line1n" ); fwrite ( $fp , "Word - 2n" ); fwrite ( $fp , "Easy As 123n" ); fclose ( $fp ); readfile ( "foo-bar.txt" ); /* The results are as follows: LINE1 WORD - 2 EASY AS 123 */

The list of streams functions in PHP is provided as follows:

 ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

stream_bucket_append函数:为队列添加数据 

stream_bucket_make_writeable函数:从操作的队列中返回一个数据对象

stream_bucket_new函数:为当前队列创建一个新的数据

stream_bucket_prepend函数:预备数据到队列 

stream_context_create函数:创建数据流上下文

stream_context_get_default函数:获取默认的数据流上下文

stream_context_get_options函数:获取数据流的设置

stream_context_set_option函数:对数据流、数据包或者上下文进行设置

stream_context_set_params函数:为数据流、数据包或者上下文设置参数

stream_copy_to_stream函数:在数据流之间进行复制操作

stream_filter_append函数:为数据流添加过滤器

stream_filter_prepend函数:为数据流预备添加过滤器

stream_filter_register函数:注册一个数据流的过滤器并作为PHP类执行

stream_filter_remove函数:从一个数据流中移除过滤器

stream_get_contents函数:读取数据流中的剩余数据到字符串

stream_get_filters函数:返回已经注册的数据流过滤器列表

stream_get_line函数:按照给定的定界符从数据流资源中获取行

stream_get_meta_data函数:从封装协议文件指针中获取报头/元数据

stream_get_transports函数:返回注册的Socket传输列表

stream_get_wrappers函数:返回注册的数据流列表

stream_register_wrapper函数:注册一个用PHP类实现的URL封装协议

stream_select函数:接收数据流数组并等待它们状态的改变

stream_set_blocking函数:将一个数据流设置为堵塞或者非堵塞状态

stream_set_timeout函数:对数据流进行超时设置

stream_set_write_buffer函数:为数据流设置缓冲区

stream_socket_accept函数:接受由函数stream_ socket_server()创建的Socket连接

stream_socket_client函数:打开网络或者UNIX主机的Socket连接

stream_socket_enable_crypto函数:为一个已经连接的Socket打开或者关闭数据加密

stream_socket_get_name函数:获取本地或者网络Socket的名称

stream_socket_pair函数:创建两个无区别的Socket数据流连接

stream_socket_recvfrom函数:从Socket获取数据,不管其连接与否

stream_socket_sendto函数:向Socket发送数据,不管其连接与否

stream_socket_server函数:创建一个网络或者UNIX Socket服务端

stream_wrapper_restore函数:恢复一个事先注销的数据包

stream_wrapper_unregister函数:注销一个URL地址包

1 2

34 5 6 7 8 9
10
11
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
stream_bucket_append function: add data to the queue stream_bucket_make_writeable function: Returns a data object from the operation queue stream_bucket_new function: Create a new data for the current queue stream_bucket_prepend function: prepare data into the queue stream_context_create function: Create a data flow context stream_context_get_default function: Get the default data flow context stream_context_get_options function: Get the settings of the data stream stream_context_set_option function: Set data stream, data packet or context stream_context_set_params function: Set parameters for data stream, packet or context stream_copy_to_stream function: copy between data streams stream_filter_append function: add a filter to the data stream stream_filter_prepend function: add filters for data stream preparation stream_filter_register function: register a data stream filter and execute it as a PHP class stream_filter_remove function: removes a filter from a data stream stream_get_contents function: Read the remaining data in the data stream into a string stream_get_filters function: returns a list of registered data stream filters stream_get_line function: Get the line from the data stream resource according to the given delimiter stream_get_meta_data function: Get header/metadata from encapsulated protocol file pointer stream_get_transports function: Returns the registered Socket transport list stream_get_wrappers function: returns the registered data stream list stream_register_wrapper function: Register a URL wrapper protocol implemented with PHP class stream_select function: receives data stream arrays and waits for their status to change stream_set_blocking function: Set a data stream to a blocking or non-blocking state stream_set_timeout function: Set timeout for data stream stream_set_write_buffer function: Set buffer for data stream stream_socket_accept function: accept the Socket connection created by the function stream_socket_server() stream_socket_client function: Open the Socket connection of the network or UNIX host stream_socket_enable_crypto function: Turn on or off data encryption for a connected Socket stream_socket_get_name function: Get the name of local or network Socket stream_socket_pair function: Create two indistinguishable Socket data stream connections stream_socket_recvfrom function: Get data from Socket, regardless of whether it is connected or not stream_socket_sendto function: Send data to Socket, regardless of whether it is connected or not stream_socket_server function: Create a network or UNIX Socket server stream_wrapper_restore function: restore a previously logged-out data package stream_wrapper_unregister function: Unregister a URL address package
http://www.bkjia.com/PHPjc/1000117.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1000117.htmlTechArticleDetailed introduction and use of PHP Streams (stream) This article mainly introduces the detailed introduction and use of PHP Streams (stream) ,PHP Streams is a built-in core operation, which may be rarely used by ordinary developers. It is used for system...
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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 Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool