预备函数:
fopen():函数将创建与文件的连接。如果是从二进制文件读取以获得跨平台兼容性,则应当将 "r" 更改为 "rb"
popen():打开进程文件指针
fsockopen():打开一个网络连接或者一个Unix套接字连接
fclose():它将关闭指向文件或 URL 的连接
feof():检测您是否已经读到文件的末尾并返回 True 或 False,如果读取的是 URL 并且套接字由于不再有任何数据可以读取而超时,则 feof 也将返回 False
filesize():文件大小(字节),因为 PHP 的整数类型是有符号整型而且很多平台使用 32 位整型,对 2GB 以上的文件,一些文件系统函数可能返回无法预期的结果 。
file_exists():文件或目录是否存在
is_readable():判断给定文件名是否可读
is_writable():判断给定的文件名是否可写
is_file():判断给定文件名是否为一个正常的文件
分段读取函数:
fgets:
string fgets ( resource $handle [, int $length ] )
从文件指针中读取一行。
handle
文件指针必须是有效的,必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。
length
从 handle 指向的文件中读取一行并返回长度最多为 length - 1 字节的字符串。碰到换行符(包括在返回值中)、EOF 或者已经读取了 length - 1 字节后停止(看先碰到那一种情况)。如果没有指定 length,则默认为 1K,或者说 1024 字节。
Note:
从 PHP 4.3 开始,忽略掉 length 则行的长度被假定为 1024,将继续从流中读取数据直到行结束。如果文件中的大多数行都大于 8KB,则在脚本中指定最大行的长度在利用资源上更为有效。
$file_handle = fopen("myfile", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $line;
}
fclose($file_handle);
fgetss:
string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )
从文件指针中读取一行并过滤掉 HTML 标记 和 fgets() 相同,只除了 fgetss() 尝试从读取的文本中去掉任何 HTML 和 PHP 标记。它使用与函数 strip_tags() 一样的机制去除标记。
handle
文件指针必须是有效的,必须指向由 fopen() 或 fsockopen() 成功打开的文件(并还未由 fclose() 关闭)。
length
取回该长度的数据。
allowable_tags
可以用可选的第三个参数指定哪些标记不被去掉。
<?php
$handle = fopen('./file.txt', 'r');
while(!feof($handle)){
echo fgetss($handle, 1024, '<br>');
}
fclose($handle);
?>
fgetc:
从文件句柄中获取一个字符。
返回一个包含有一个字符的字符串,该字符从 handle 指向的文件中得到。 碰到 EOF 则返回 FALSE。此函数可能返回布尔值 FALSE,但也可能返回等同于 FALSE 的非布尔值。请阅读 布尔类型章节以获取更多信息。应使用 === 运算符来测试此函数的返回值。
<?php
$fp = fopen('somefile.txt', 'r');
if (!$fp) {
echo 'Could not open file somefile.txt';
}
while (false !== ($char = fgetc($fp))) {
echo "$char\n";
}
?>
fread:
string fread ( resource $handle , int $length )
读取文件(可安全用于二进制文件)
handle
文件系统指针,是典型地由 fopen() 创建的 resource(资源)。
length
最多读取 length 个字节。不管指定多少字节,fread 都不会读取超过 8,192 个字节 (8 KB)。
读取终止条件:
读取了 length 个字节
到达了文件末尾(EOF)
套接字超时情况(网络流)
如果流是读取缓冲并且不代表一个普通文件,最多一个读到的字节数相等的块大小(通常是8192),根据之前缓冲数据,返回数据的大小可能大于块大小。
$handle = fopen('http://www.baidu.com', 'r');
$content = '';
while(!feof($handle)){
$content .= fread($handle, 8080);
}
echo $content;
fclose($handle);
当从任何不是普通本地文件读取时,例如在读取从远程文件或 popen() 以及 fsockopen() 返回的流时,读取会在一个包可用之后停止。这意味着应该如下例所示将数据收集起来合并成大块。
<?php
// 对 PHP 5 及更高版本
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle = fopen("http://www.example.com/", "rb");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);
?>
如果只是想将一个文件的内容读入到一个字符串中,用 file_get_contents(),它的性能比上面的代码好得多。
fscanf:
mixed fscanf ( resource $handle , string $format [, mixed &$... ] )
fscanf() 函数和 sscanf() 相似,但是它从与 handle 关联的文件中接受输入并根据指定的 format(定义于 sprintf() 的文档中)来解释输入。从文件中格式化输入
每次调用 fscanf() 都会从文件中读取一行。
handle
文件系统指针,是典型地由 fopen() 创建的 resource(资源)。
format
参数格式是 sprintf() 文档中所描述的格式。
...
The optional assigned values.
<?php
$handle = fopen("users.txt", "r");
while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {
list ($name, $profession, $countrycode) = $userinfo;
//... do something with the values
}
fclose($handle);
?>
fpassthru:
int fpassthru ( resource $handle )
将给定的文件指针从当前的位置读取到 EOF 并把结果写到输出缓冲区。 输出文件指针处的所有剩余数据
如果已经向文件写入数据,就必须调用 rewind() 来将文件指针指向文件头。
如果既不修改文件也不在特定位置检索,只想将文件的内容下载到输出缓冲区,应该使用 readfile(),这样可以省去 fopen() 调用。
<?php
// 以二进制格式打开文件
$name = './img/ok.png';
$fp = fopen($name, 'rb');
// 发送合适的报头
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// 发送图片并终止脚本
fpassthru($fp);
exit;
?>
读取整个文件函数
file:
array file ( string $filename [, int $flags = 0 [, resource $context ]] )
把整个文件读入一个数组中。二进制安全
filename
文件的路径。
flags
可选参数 flags 可以是以下一个或多个常量:
FILE_USE_INCLUDE_PATH 在 include_path 中查找文件。
FILE_IGNORE_NEW_LINES 在数组每个元素的末尾不要添加换行符
FILE_SKIP_EMPTY_LINES 跳过空行
context A context resource created with the stream_context_create() function.
Note: 在 PHP 5.0.0 中增加了对上下文(Context)的支持。有关上下文(Context)的说明参见 Streams。
<?php
// 将一个文件读入数组。本例中通过 HTTP 从 URL 中取得 HTML 源文件。
$lines = file('http://www.example.com/');
// 在数组中循环,显示 HTML 的源文件并加上行号。
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// 另一个例子将 web 页面读入字符串。参见 file_get_contents()。
$html = implode('', file('http://www.example.com/'));
// 从 PHP 5 开始可以使用可选标记参数
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>
readfile:
int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )
读入一个文件并写入到输出缓冲。输出一个文件
filename
要读取的文件名。
use_include_path
如果也想在 include_path 中搜索文件,可以使用可选的第二个参数并将其设为 TRUE。
context
A context stream resource.
返回从文件中读入的字节数
<?php
$file = 'monkey.gif';
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>
file_get_contents:
string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
和 file() 一样,只除了 file_get_contents() 把文件读入一个字符串。将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE。将整个文件读入一个字符串
file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。
Note:
如果要打开有特殊字符的 URL (比如说有空格),就需要使用 urlencode() 进行 URL 编码。
filename
要读取的文件的名称or url。
use_include_path FILE_USE_INCLUDE_PATH
context
A valid context resource created with stream_context_create(). 如果你不需要自定义 context,可以用 NULL 来忽略。
offset
在原流的偏移量开始读取(只适用于流和本地文件,试图用于远程文件不可预知)
maxlen
读取数据的最大长度,默认全部读取,请注意,此参数用于过滤处理流。
读取指定位置数据:
<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./people.txt', NULL, NULL, 20, 14);
var_dump($section);
?>
使用context:
function file_get_contents_use_post($uri,$data=array()){
if(empty($data)){ return file_get_contents($uri);}
$postdata = http_build_query($data);
$opts = array('http' =>
array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded; charset=UTF-8',
'content' => $postdata,
'timeout' => 60
)
/*
$headers = "POST ".$url['protocol'].$url['host'].$url['path']." HTTP/1.0".PHPEOL.
"Host: ".$url['host'].PHPEOL.
"Referer: ".$url['protocol'].$url['host'].$url['path'].PHPEOL.
"Content-Type: application/x-www-form-urlencoded".PHPEOL.
"Content-Length: ".strlen($url['query']).PHPEOL.
"Authorization: Basic ".base64_encode("$https_user:$https_password").PHPEOL.
$url['query'];
Accept:* / *
Accept-Encoding:gzip, deflate
Accept-Language:zh,zh-CN;q=0.8
Connection:keep-alive
Content-Length:136
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:xxx
Origin:http://www.baidu.com
Referer:http://www.baidu.com/
User-Agent:Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36
X-Requested-With:XMLHttpRequest
*/
);
$context = stream_context_create($opts);
return file_get_contents($uri, false, $context);
}
parse_ini_file:(parse_ini_string)
array parse_ini_file ( string $filename [, bool $process_sections = false [, int $scanner_mode = INI_SCANNER_NORMAL ]] )
载入一个由 filename 指定的 ini 文件,并将其中的设置作为一个联合数组返回。解析一个配置文件
ini 文件的结构和 php.ini 的相似。
filename
要解析的 ini 文件的文件名。
process_sections
如果将最后的 process_sections 参数设为 TRUE,将得到一个多维数组,包括了配置文件中每一节的名称和设置。process_sections 的默认值是 FALSE。
scanner_mode
Can either be INI_SCANNER_NORMAL (default) or INI_SCANNER_RAW. If INI_SCANNER_RAW is supplied, then option values will not be parsed.
成功时以关联数组 array 返回设置,失败时返回 FALSE。
注意:
本函数和 php.ini 文件没有关系,该文件在运行脚本时就已经处理过了。本函数可以用来读取你自己的应用程序的配置文件。
如果 ini 文件中的值包含任何非字母数字的字符,需要将其括在双引号中(")。
有些保留字不能作为 ini 文件中的键名,包括:null,yes,no,true 和 false。值为 null,no 和 false 等效于 "",值为 yes 和 true 等效于 "1"。字符 {}|&~![()" 也不能用在键名的任何地方,而且这些字符在选项值中有着特殊的意义。
样列ini文本:
[personal information]
name = "King Arthur"
quest = To seek the holy grail
favorite color = Blue
[more stuff]
Samuel Clemens = Mark Twain
Caryn Johnson = Whoopi Goldberg
$file_array = parse_ini_file("holy_grail.ini");
print_r($file_array);
$file_array = parse_ini_file("holy_grail.ini", true);
print_r($file_array);
分别输出:
Array
(
[name] => King Arthur
[quest] => To seek the Holy Grail
[favorite color] => Blue
[Samuel Clemens] => Mark Twain
[Caryn Johnson] => Whoopi Goldberg
)
Array
(
[personal information] => Array
(
[name] => King Arthur
[quest] => To seek the Holy Grail
[favorite color] => Blue
)
[more stuff] => Array
(
[Samuel Clemens] => Mark Twain
[Caryn Johnson] => Whoopi Goldberg
)
)
命令进化:
$my_file = file_get_contents("myfilename");
echo $my_file;
===>
echo file_get_contents("myfilename");
===>
echo file_get_contents("http://127.0.0.1/");
$fh = fopen("http://127.0.0.1/", "r");
fpassthru($fh);
===>
readfile("http://127.0.0.1/");
$array = split("\n", file_get_contents("myfile"));
===>
$array = file("myfile");
$filename = "myfile";
if (file_exists($filename) && is_readable ($filename)) {
<span style="white-space:pre"> </span>$fh = fopen($filename, "r");
<span style="white-space:pre"> </span># Processing
<span style="white-space:pre"> </span>fclose($fh);
}
===>
if ($fh = fopen($filename, "r")) {
<span style="white-space:pre"> </span># Processing
<span style="white-space:pre"> </span>fclose($fh);
}
文件位置函数:
fseek:
int fseek ( resource $handle , int $offset [, int $whence = SEEK_SET ] )
在与 handle 关联的文件中设定文件指针位置。 新位置从文件头开始以字节数度量,是以 whence 指定的位置加上 offset。在文件指针中定位
handle
文件系统指针,是典型地由 fopen() 创建的 resource(资源)。
offset
偏移量。
要移动到文件尾之前的位置,需要给 offset 传递一个负值,并设置 whence 为 SEEK_END。
whence
SEEK_SET - 设定位置等于 offset 字节。
SEEK_CUR - 设定位置为当前位置加上 offset。
SEEK_END - 设定位置为文件尾加上 offset。
成功则返回 0;否则返回 -1。注意移动到 EOF 之后的位置不算错误。
示例:
跳转回文件的开头
fseek($fh, 0);
从当前位置向前跳转 100 个字节,则可以尝试使用:
fseek($fh, 100, SEEK_CUR);
向后跳转 100 个字节:
fseek($fh, -100, SEEK_CUR);
向后跳转至文件末尾前 100 个字节处。
fseek($fh, -100, SEEK_END);
在到达新位置后,可以使用 fgets、fscanf 或任何其他方法读取数据。
注:不能将 fseek 用于引用 URL 的文件处理。
ftell:
int ftell ( resource $handle )
返回由 handle 指定的文件指针的位置,也就是文件流中的偏移量。返回文件指针读/写的位置
handle
文件指针必须是有效的,且必须指向一个通过 fopen() 或 popen() 成功打开的文件。在附加模式(加参数 "a" 打开文件)中 ftell() 会返回未定义错误。
<?php
$file = fopen('counter.txt', 'w');
fwrite($file, '123456789');
fclose($file);
$file = fopen('counter.txt', 'r');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);
$file = fopen('counter.txt', 'a+');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);
$file = fopen('counter.txt', 'r+');
fwrite($file, 'rr');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);
$file = fopen('counter.txt', 'a+');
fwrite($file, 'aa');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;//返回未定义错误
fclose($file);
$file = fopen('counter.txt', 'r');
echo ftell($file) . ' "' . fgets($file) . '" ' . ftell($file) . PHP_EOL;
fclose($file);
?>
Result:
0 "123456789" 9
0 "123456789" 9
2 "3456789" 9
2 "" 2
0 "rr3456789aa" 11
rewind:
bool rewind ( resource $handle )
将 handle 的文件位置指针设为文件流的开头。倒回文件指针的位置
handle
文件指针必须合法,并且指向由 fopen() 成功打开的文件。
成功时返回 TRUE, 或者在失败时返回 FALSE。
Note:
如果将文件以附加("a" 或者 "a+")模式打开,写入文件的任何数据总是会被附加在后面,不管文件指针的位置。
参数
<?php
$handle = fopen('output.txt', 'r+');
fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);
echo fread($handle, filesize('output.txt'));//Foolly long sentence.
fclose($handle);
?>
流相关函数:
stream_get_contents:
string stream_get_contents ( resource $handle [, int $maxlength = -1 [, int $offset = -1 ]] )
与 file_get_contents() 一样,但是 stream_get_contents() 是对一个已经打开的资源流进行操作,并将其内容写入一个字符串返回。 返回的内容取决于 maxlength 字节长度和 offset 指定的起始位置。读取资源流到一个字符串
handle (resource)
一个资源流(例如 fopen() 操作之后返回的结果)
maxlength (integer)
需要读取的最大的字节数。默认是-1(读取全部的缓冲数据)。
offset (integer)
在读取数据之前先查找指定的偏移量。如果这个数字是负数,就不进行查找,直接从当前位置开始读取。
if ($stream = fopen('http://www.example.com', 'r')) {
// print all the page starting at the offset 10
echo stream_get_contents($stream, -1, 10);
fclose($stream);
}
if ($stream = fopen('http://www.example.net', 'r')) {
// print the first 5 bytes
echo stream_get_contents($stream, 5);
fclose($stream);
}
stream_get_line:
string stream_get_line ( resource $handle , int $length [, string $ending ] )
从给定的资源流里读取一行。从资源流里读取一行直到给定的定界符
当读取到 length 个字节数就结束,或者当在读取的字符串中发现 ending (不包含到返回值里)也结束,又或者遇到了 EOF 也结束(总之以上条件中哪个先出现就以哪个为准)。
这个函数与 fgets() 几乎是相同的,唯一的区别是在这个函数里面允许指定行尾的定界符,而不是使用标准的 \n, \r 还有 \r\n ,并且返回值中不包含定界符。(翻译注:也可以把 \n 等作为定界符传入 ending )
handle
一个有效的文件句柄。
length
需要从句柄里读取的字节数。
ending
可选参数,字符串定界符。
返回一个字符串,该字符串的内容根据 length 字节数从 handle 里读取。
如果发生错误,则返回 FALSE.
stream_context_create:
resource stream_context_create ([ array $options [, array $params ]] )
创建病返回一个资源流上下文,该资源流中包含了 options 中提前设定的所有参数的值。创建资源流上下文
options
必须是一个二维关联数组,格式如下:$arr['wrapper']['option'] = $value 。
默认是一个空数组。
params
必须是 $arr['parameter'] = $value 格式的关联数组。 请参考 context parameters 里的标准资源流参数列表。
返回上下文资源流,类型为 resource 。
<?php
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
with additional headers shown above */
$fp = fopen('http://www.example.com', 'r', false, $context);
fpassthru($fp);
fclose($fp);
?>
option多种写法:
$options = array(
'http'=>array(
'method'=>"POST",
'header'=>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content'=>http_build_query(array('foo'=>'bar'))
));
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>array("Accept-language: en",
"Cookie: foo=bar",
"Custom-Header: value")
)
);
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$opts = array('ftp' => array(
'proxy' => 'tcp://vbinprst10:8080',
'request_fulluri'=>true,
'header' => array(
"Proxy-Authorization: Basic $auth"
)
),
'http' => array(
'proxy' => 'tcp://vbinprst10:8080',
'request_fulluri'=>true,
'header' => array(
"Proxy-Authorization: Basic $auth"
)
)
);
$opts = array(
'http'=> array(
'method'=> "GET",
'header'=> array( "Cookie: foo="bar"l ),
'user_agent'=> $_SERVER['HTTP_USER_AGENT']
)
);
$context_options = array (
'https' => array (
'method' => 'POST',
'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
. "Content-Length: " . strlen($data) . "\r\n",
'content' => $data
)
);
更多选项访问: PHP stream相关协议及上下文选项和参数归纳
stream_get_meta_data — 从封装协议文件指针中取得报头/元数据
array stream_get_meta_data ( int $fp )
返回现有 stream 的信息。可以是任何通过 fopen(),fsockopen() 和 pfsockopen() 建立的流。返回的数组包含以下项目:
timed_out (bool) - 如果在上次调用 fread() 或者 fgets() 中等待数据时流超时了则为 TRUE。
blocked (bool) - 如果流处于阻塞 IO 模式时为 TRUE。参见 stream_set_blocking()。
eof (bool) - 如果流到达文件末尾时为 TRUE。注意对于 socket 流甚至当 unread_bytes 为非零值时也可以为 TRUE。要测定是否有更多数据可读,用 feof() 替代读取本项目的值。
unread_bytes (int) - 当前在 PHP 自己的内部缓冲区中的字节数。
Note: 不要在脚本中使用此值。
以下项目是 PHP 4.3 新加的:
stream_type (string) - 一个描述流底层实现的标注。
wrapper_type (string) - 一个描述流的分层协议封装实现的标注。更多关于封装协议的信息见 支持的协议和封装协议。
wrapper_data (mixed) - 当前流附加的封装协议数据。更多封装协议及其数据的信息见 支持的协议和封装协议。
filters (array) - 包含有被叠加在当前流的任何过滤器名的数组。过滤器的文档见附录中的可用过滤器列表。
Note:
本函数是 PHP 4.3 引进的,在此版本之前,可以用 socket_get_status() 来取得前四个项目并且仅能用于基于 socket 的流。
在 PHP 4.3 及以后版本中,socket_get_status() 是本函数的别名。
Note: 本函数不能作用于通过 Socket 扩展库创建的流。
以下项目为 PHP 5.0 新加:
mode (string) - 对当前流所要求的访问类型(见 fopen() 中的表格 1)。
seekable (bool) - 是否可以在当前流中定位。
uri (string) - 与当前流关联的 URI 或文件名。
stream_context_get_options — 获取资源流/数据包/上下文的参数
array stream_context_get_options ( resource $stream_or_context )
返回指定资源流或者上下文的数组参数。
<?php
$params = array("method" => "POST");
stream_context_get_default(array("http" => $params));
var_dump(stream_context_get_options(stream_context_get_default()));
?>
其他流函数:
stream_filter_remove — 从资源流里移除某个过滤器
stream_get_contents — 读取资源流到一个字符串
stream_get_filters — 获取已注册的数据流过滤器列表
stream_get_line — 从资源流里读取一行直到给定的定界符
stream_get_transports — 获取已注册的套接字传输协议列表
stream_get_wrappers — 获取已注册的流类型
stream_register_wrapper — 注册一个用 PHP 类实现的 URL 封装协议
stream_context_set_option — 对资源流、数据包或者上下文设置参数
stream_encoding — 设置数据流的字符集