File operations are a fundamental and frequently used feature in PHP development. File reading is used to obtain the contents of a file, while file writing saves data to a file. This article will thoroughly explain various PHP file reading and writing methods, paired with example code to help you easily master file handling skills.
fopen() is the most basic PHP file operation function that opens a file and returns a file resource handle. It requires the filename and mode as parameters. Common modes include:
Example code:
$file = fopen("file.txt", "r"); if ($file) { while (($line = fgets($file)) !== false) { echo $line; } fclose($file); }
The file_get_contents() function reads the entire file into a string at once. It's very convenient — just pass the file path.
$fileContent = file_get_contents("file.txt"); echo $fileContent;
fread() is often used together with fopen() to read a specified length of file content. It takes the file resource and length as parameters.
$file = fopen("file.txt", "r"); if ($file) { $content = fread($file, filesize("file.txt")); echo $content; fclose($file); }
fopen() can also open files for writing by setting the mode to "w" (write, overwrite) or "a" (append).
$file = fopen("file.txt", "w"); if ($file) { fwrite($file, "Hello, World!"); fclose($file); }
file_put_contents() is a convenient function for writing to files without explicitly opening them first. Just provide the filename and the content.
file_put_contents("file.txt", "Hello, World!");
fwrite() writes content to an already opened file resource, usually with fopen().
$file = fopen("file.txt", "w"); if ($file) { fwrite($file, "Hello, World!"); fclose($file); }
This article introduced commonly used PHP file reading and writing functions, including fopen, file_get_contents, fread, file_put_contents, and fwrite, with practical examples to demonstrate how to efficiently handle files. Choosing the appropriate method based on your needs makes file operations simple and effective.