Home >Backend Development >PHP Tutorial >What PHP functions are available for file operations?

What PHP functions are available for file operations?

WBOY
WBOYOriginal
2024-04-20 09:45:011010browse

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 函数可用于文件操作?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn