Latest web development tutorials

PHP fopen () function

PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual

Definition and Usage

fopen () function to open a file or URL.

If fopen () fails, it returns FALSE with an error message. You can add a function name in front of the '@' to hide the error output.

grammar

fopen(filename,mode,include_path,context)

参数 描述
filename 必需。规定要打开的文件或 URL。
mode 必需。规定您请求到该文件/流的访问类型。

可能的值:

  • "r" (只读方式打开,将文件指针指向文件头)
  • "r+" (读写方式打开,将文件指针指向文件头)
  • "w" (写入方式打开,清除文件内容,如果文件不存在则尝试创建之)
  • "w+" (读写方式打开,清除文件内容,如果文件不存在则尝试创建之)
  • "a" (写入方式打开,将文件指针指向文件末尾进行写入,如果文件不存在则尝试创建之)
  • "a+" (读写方式打开,通过将文件指针指向文件末尾进行写入来保存文件内容)
  • "x" (创建一个新的文件并以写入方式打开,如果文件已存在则返回 FALSE 和一个错误)
  • "x+" (创建一个新的文件并以读写方式打开,如果文件已存在则返回 FALSE 和一个错误)
include_path 可选。如果您还想在 include_path(在 php.ini 中)中搜索文件的话,请设置该参数为 '1'。
context 可选。规定文件句柄的环境。context 是一套可以修改流的行为的选项。


Tips and Notes

Note: When writing a text file, make sure you use the correct line endings!In Unix systems, the line endings to \ n; Windows systems, line endings to \ r \ n; Macintosh systems, line endings to \ r. Windows systems provide a text converter labeled "t", which will transparently translate \ n \ r \ n. You can also use the "b" to force binary mode, so it will not convert the data. To use these tags, please use the "b" or "t" as the last character of the mode parameter.


Examples

<?php
$file = fopen("test.txt","r");
$file = fopen("/home/test/test.txt","r");
$file = fopen("/home/test/test.gif","wb");
$file = fopen("http://www.example.com/","r");
$file = fopen("ftp://user:[email protected]/test.txt","w");
?>


PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual