美文网首页
PHP文件和目录相关问题

PHP文件和目录相关问题

作者: 陈智涛 | 来源:发表于2017-10-30 11:25 被阅读0次

一、文件的读取和写入操作

1.1 fopen

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

fopen打开模式:

屏幕快照 2017-10-29 上午11.22.00.png

1.2 fwrite

写入文件(可安全用于二进制文件)

int fwrite ( resource $handle , string $string [, int $length ] )

fwrite() 把 string 的内容写入 文件指针 handle 处。

1.3 fputs

fputs — fwrite() 的别名

1.4 fread()

fread — 读取文件(可安全用于二进制文件)

string fread ( resource $handle , int $length )

1.5 fgets()

fgets — 从文件指针中读取一行

string fgets ( resource $handle [, int $length ] )  

1.6 fgetc()

fgetc — 从文件指针中读取字符

string fgetc ( resource $handle )

1.7 fclose()

关闭文件
fclose — 关闭一个已打开的文件指针

bool fclose ( resource $handle )

不需要fopen打开的函数

1 file_get_contents
file_get_contents — 将整个文件读入一个字符串

string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>

2 file_put_contents
file_put_contents — 将一个字符串写入文件

int file_put_contents ( string $filename, mixed $data[, int $flags= 0 [, resource $context]] )

和依次调用 fopen()fwrite() 以及 fclose() 功能一样。

1.8 file()

把整个文件读入一个数组中

array file ( string $filename [, int $flags = 0 [, resource $context ]] )
<?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);
?>

1.9 readfile()

readfile — 输出文件
读取文件并写入到输出缓冲。

int readfile ( string $filename [, bool $use_include_path = false [, resource $context ]] )

2.0 访问远程文件

在 php.ini 开启allow_url_fopen
示例1:在text.txt文件头部持续写入"hello wolrd"

<?php
$f = fopen("text.txt",'r');
$content = fread($f,filesize("text.txt"));
$content = "hello world\n".$content;
fclose($f);
$f = fopen("text.txt",'w');
fwrite($f,$content);
fclose($f);

二、目录相关操作

相关文章

网友评论

      本文标题:PHP文件和目录相关问题

      本文链接:https://www.haomeiwen.com/subject/egcfpxtx.html