PHP complete se...LOGIN
PHP complete self-study manual
author:php.cn  update time:2022-04-15 13:53:54

PHP files



fopen() function is used to open a file in PHP.


Open File

fopen() function is used to open a file in PHP.

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

<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
files may be opened through the following modes To open:
ModeDescription
rRead only . Start at the beginning of the file.
r+Read/write. Start at the beginning of the file.
wWrite only. Opens and clears the contents of the file; if the file does not exist, creates a new file.
w+Read/write. Opens and clears the contents of the file; if the file does not exist, creates a new file.
aAppend. Opens and writes to the end of the file, or creates a new file if it does not exist.
a+Read/Append. Maintain file contents by writing to the end of the file.
xWrite only. Create new file. If the file already exists, returns FALSE and an error.
x+Read/write. Create new file. If the file already exists, returns FALSE and an error.

Comments: If the fopen() function cannot open the specified file, it returns 0 (false).

Example

If the fopen() function cannot open the specified file, the following example will generate a message:

<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 the open file:

<?php
$file = fopen("test.txt","r");
//执行一些代码
fclose($file);
?>

Detect the end of file (EOF )

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

The feof() function is useful when looping through data of unknown length.

Note: In w, a and x modes, you cannot read open files!

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

Read the file line by line

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

Comments: After calling this function, the file pointer will move to the next line.

Example

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

<?php
$file = fopen("welcome.txt", "r") or exit("无法打开文件!");
// 读取文件每一行,直到文件结尾
while(!feof($file))

  {
    echo fgets($file). "<br>";

  }
fclose($file);
?>

One by one Character reading file

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

Note: After calling this function, the file pointer will move to the next character.

Example

The following example reads the file character by character until the end of the file:

<?php
$file=fopen("welcome.txt","r") or exit("无法打开文件!");
while (!feof($file))

  {
    echo fgetc($file);

  }
fclose($file);
?>

## PHP Filesystem Reference Manual

For a complete reference manual for PHP filesystem functions, please visit our

PHP Filesystem Reference Manual.