PHP 中的 fopen() 函数
phpprogrammingserver side programming
fopen() 函数打开一个文件或 URL。如果函数失败,则返回 FALSE 和失败错误。在函数名称前面添加 '@' 以隐藏错误输出。
语法
fopen(file_path, mode, include_path, context)
参数
file_path − 文件的路径。
mode − 您需要对文件的访问类型
- “r” - 只读
- "r+" - 读/写
- "w" - 只写
- "w+" - 读/写
- "a" - 只写。打开并写入文件末尾,如果文件不存在则创建新文件)
- "a+" - 读/写。通过写入文件末尾来保留文件内容)
- "x" - 只写。创建新文件。如果文件已存在,则返回 FALSE 和错误)
- "x+" - 读/写。创建新文件。如果文件已存在,则返回 FALSE 和错误)
incude_path − 将其设置为 '1'如果您还想在 include_path(在 php.ini 中)中搜索该文件。
context − 文件指针的上下文。
返回
fopen() 函数在失败时返回 FALSE 和错误。在函数名称前面添加 '@' 以隐藏错误输出。
假设我们有一个文件 “new.txt”,内容如下。
The content of the file!
现在让我们看一个例子 −
示例
<?php // 读/写模式 $file_pointer = fopen("new.txt", 'r+') or die("File does not exist"); $res = fgets($file_pointer); echo $res; fclose($ile_pointer); ?>
输出
The content of the file!
让我们看一个“one.txt”文件的示例。
示例
<?php // 读/写模式 $file_pointer = fopen("one.txt", "w+"); // 写入文件 fwrite($file_pointer, 'demo content'); echo fread($file_pointer, filesize("new.txt")); fclose($file_pointer); ?>
输出
demo content