Table of Contents
PHP Streams(流)详细介绍及使用,phpstreams
Home php教程 php手册 PHP Streams(流)详细介绍及使用,phpstreams

PHP Streams(流)详细介绍及使用,phpstreams

Jun 13, 2016 am 09:04 AM
php streams introduce use flow

PHP Streams(流)详细介绍及使用,phpstreams

PHP Streams是内置核心操作,可能一般的开发者很少用,它用于统一文件、网络、数据压缩等类文件操作方式,并为这些类文件操作提供一组通用的函数接口。

一个stream就是一个具有流式行为的资源对象,每个stream对象都有一个包装类。Stream 可以通过://方式来引用。其中是包装类的名字,中的内容是由包装类的语法指定,不同的包装类的语法会有所不同。
来看看PHP 默认有哪些内置的包装类:

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
)
*/
Copy after login

看看PHP手册中关于PHP支持的协议和包装类。
看下面一段使用file_get_contents()获取数据的代码:

/* 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" );
Copy after login

实际上readfile('/path/to/somefile.txt')或者readfile('file:///path/to/somefile.txt'),这两种方式是等效的。因为PHP的默认包装类就是file://。

手册上明确指出,可以通过stream_register_wrapper()注册自己的包装器 ,可以去看看手册中的例子。
OK,这里简单介绍一个PHP://,它是PHP用来处理IO流的包装类(点击这里看个例子)。通过PHP://可以访问更强大的输入输出流:

php://stdin:访问PHP进程相应的输入流,比如用在获取cli执行脚本时的键盘输入。
php://stdout:访问PHP进程相应的输出流。
php://stderr:访问PHP进程相应的错误输出。
php://input:访问请求的原始数据的只读流。
php://output:只写的数据流,以 print 和 echo 一样的方式写入到输出区。
php://fd:允许直接访问指定的文件描述符。例 php://fd/3 引用了文件描述符 3。
php://memory:允许读写临时数据。 把数据储存在内存中。
php://temp:同上,会在内存量达到预定义的限制后(默认是 2MB)存入临时文件中。
php://filter:过滤器。

PHP还可以通过context和filter对包装类进行修饰和增强。
(1)关于context,如PHP通过stream_context_create()来设置获取文件超时时间,这段代码大家肯定用过:

$opts = array(
  'http'=>array(
    'method'=>"GET",
    'timeout'=>60,
  )
);
$context = stream_context_create($opts);
$html =file_get_contents('http://www.bkjia.com', false, $context);
Copy after login

(2)关于filter过滤器,首先来看看PHP有哪些内置的过滤器:

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.*
)
*/
Copy after login

通过stream_filter_register()和内置的php_user_filter可创建自定义的过滤器,如下:

/* 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 , "Line1\n" );
fwrite ( $fp , "Word - 2\n" );
fwrite ( $fp , "Easy As 123\n" );
 
fclose ( $fp );
 
 
readfile ( "foo-bar.txt" );
/*
结果如下:
LINE1
WORD - 2
EASY AS 123
*/

Copy after login

提供PHP中streams函数列表如下:

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地址包
Copy after login

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles