Latest web development tutorials

PHP File

fopen () function is used to open files in PHP.


open a file

fopen () function is used to open files in PHP.

The first parameter of this function contains the name of the file you want to open, and the second parameter specifies which mode to use to open the file:

<Html>
<Body>

<? Php
$ File = fopen ( "welcome.txt", "r");
?>

</ Body>
</ Html>

File may be opened by the following modes:

模式 描述
r 只读。在文件的开头开始。
r+ 读/写。在文件的开头开始。
w 只写。打开并清空文件的内容;如果文件不存在,则创建新文件。
w+ 读/写。打开并清空文件的内容;如果文件不存在,则创建新文件。
a 追加。打开并向文件末尾进行写操作,如果文件不存在,则创建新文件。
a+ 读/追加。通过向文件末尾写内容,来保持文件内容。
x 只写。创建新文件。如果文件已存在,则返回 FALSE 和一个错误。
x+ 读/写。创建新文件。如果文件已存在,则返回 FALSE 和一个错误。

Note: If thefopen () function does not open the specified file, it returns 0 (false).

Examples

If the fopen () function does not open the specified file, the following example will generate some news:

<Html>
<Body>

<? Php
$ File = fopen ( "welcome.txt", "r") or exit ( "Unable to open file!");
?>

</ Body>
</ Html>


Close the file

fclose () function is used to close an open file:

<?php
$file = fopen("test.txt","r");

//执行一些代码

fclose($file);
?>


End detecting file (EOF)

Are feof () function detects the end of file has been reached (EOF).

When looping through data of unknown length, feof () function is useful.

NOTE: In w, a, and x mode, you can not open the file read!

if (feof($file)) echo "文件结尾";


Read the file line by line

fgets () function is used to read the file line by line from the file.

Note: After a call to this function the file pointer moves to the next line.

Examples

The following example reads the file line by line, until the end of the file so far:

<? Php
$ File = fopen ( "welcome.txt", "r") or exit ( "Unable to open file!");
// Read the file each line, until the end of the file
while (! feof ($ file))
{
. Echo fgets ($ file) "<br>";
}
fclose ($ file);
?>


Read a file character by character

fgetc () function is used to read a file character by character from a file.

Note: After a call to this function the file pointer moves to the next character.

Examples

The following example reads a file character by character, until the end of the file so far:

<? Php
$ File = fopen ( "welcome.txt", "r") or exit ( "Unable to open file!");
while (! feof ($ file))
{
echo fgetc ($ file);
}
fclose ($ file);
?>


PHP Filesystem Reference Manual

For a complete reference manual PHP filesystem functions, visit our PHP Filesystem Reference Manual .