當前位置:才華齋>設計>網頁設計>

關於PHP中的流介紹

網頁設計 閱讀(1.1W)

PHP是一種 HTML 內嵌式的語言,是一種在服務器端執行的嵌入HTML文件的指令碼語言,語言的風格有類似於C語言,被廣泛地運用。

關於PHP中的流介紹

概述

流(streams)是PHP4.3版本引入的一個特性,主要是為了統一檔案、sockets以及其他類似資源的工作方法。PHP4.3距今已經有很長時間了,但是很多程式設計師似乎都不能正確使用PHP中的流,當然這也包括我。以前也在一些程式中遇到過流的使用,如php://input,但是一直沒機會整理,今天就把這部分知識整理下。

流是由PHP提供的'資源,可以供我們透明的使用,而且流是一個非常強大的工具。適當的在程式中使用流,可以將我們的程式帶到一個新的高度。

PHP手冊中對流的描述如下:

複製程式碼 程式碼如下:

Streams were introduced with PHP 4.3.0 as a way of generalizing file, network, data compression, and other operations which share a common set of functions and uses. In its simplest definition, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary locations within the stream.

每一種流都實現了一個包裝器(wrapper),包裝器包含一些額外的程式碼用來處理特殊的協議和編碼。PHP提供了一些內建的包裝器,我們也可以很輕鬆的建立和註冊自定義的包裝器。我們甚至可以使用上下文(contexts)和過濾器來改變和增強包裝器。

流基礎知識

PHP中流的形式如:://。是包裝器的名字,的內容取決於不同的包裝器語法。

預設的包裝器是file://,也就是說每次我們訪問檔案系統的時候都使用了流。例如,我們可以使用如下兩種方式來讀取檔案:readfile(/path/to/)和readfile(file:///path/to/),使用這兩種方式讀取檔案,可以得到相同的結果。

正如前面所說,PHP提供了一些內建的包裝器、協議和過濾器。檢視我們的機器上安裝了哪些包裝器,可以使用如下幾個函式:

複製程式碼 程式碼如下:

var_dump(stream_get_transports());

var_dump(stream_get_wrappers());

var_dump(stream_get_filters());

>

我本地的環境輸出內容如下:

複製程式碼 程式碼如下:

array (size=8)

0 => string tcp (length=3)

1 => string udp (length=3)

2 => string unix (length=4)

3 => string udg (length=3)

4 => string ssl (length=3)

5 => string sslv3 (length=5)

6 => string sslv2 (length=5)

7 => string tls (length=3)

array (size=12)

0 => string https (length=5)

1 => string ftps (length=4)

2 => string (length=13)

3 => string 2 (length=14)

4 => string php (length=3)

5 => string file (length=4)

6 => string glob (length=4)

7 => string data (length=4)

8 => string http (length=4)

9 => string ftp (length=3)

10 => string phar (length=4)

11 => string zip (length=3)

array (size=12)