Home >Backend Development >PHP Tutorial >What PHP functions are available for file operations?
PHP provides the following file operation functions: Open a file: fopen (file path, mode) Read a file: fread (file handle, number of bytes), fgets (file handle) Write a file: fwrite (file handle, new content )Close the file: fclose(file handle)
PHP File Operation Function Guide
PHP provides a series of functions that can help You perform various file operations. This guide will introduce you to these functions and provide some practical examples to show how to use them.
Open a file
To open a file, use fopen()
Function:
$handle = fopen("myfile.txt", "r");
This function returns a file handle , for subsequent operations. The first argument is the file path, and the second argument is the mode, such as "r" (read), "w" (write), or "a" (append).
Reading a file
To read a file, use the fread()
or fgets()
function:
$content = fread($handle, 1024); // 读取 1024 字节 $line = fgets($handle); // 读取一行
Write to File
To write to a file, use fwrite()
Function:
fwrite($handle, "新内容");
Close File
After the operation is completed, be sure to close the file:
fclose($handle);
Practical case
Read a file
$handle = fopen("myfile.txt", "r"); $content = fread($handle, filesize("myfile.txt")); fclose($handle); echo $content;
Write a file
$handle = fopen("myfile.txt", "w"); fwrite($handle, "新内容"); fclose($handle);
The above is the detailed content of What PHP functions are available for file operations?. For more information, please follow other related articles on the PHP Chinese website!