In the development process, file operations are inevitable, especially when reading configuration files, log files, or writing data to files. PHP provides several functions for file read/write operations, and this article will introduce these operations in detail, with common code examples.
PHP offers multiple file reading functions, such as file_get_contents(), fopen(), fgets(), fread(), and file(). Let's demonstrate file reading using file_get_contents() as an example.
Code Example:
$file = "example.txt"; $content = file_get_contents($file); echo $content;
The above code will read the content of the "example.txt" file and output it to the page.
Sometimes, we need to read a file line by line and process each line individually. We can use fgets() or fread() functions for this. Here’s an example:
Code Example:
$file = "example.txt"; if ($handle = fopen($file, 'r')) { while (!feof($handle)) { $line = fgets($handle); echo $line . "<br/>"; } fclose($handle); }
This code will read the content of the "example.txt" file line by line, outputting each line to the page with a
tag for line breaks.
PHP provides multiple file writing functions, such as file_put_contents(), fopen(), and fwrite(). Below, we’ll demonstrate how to write to a file using the file_put_contents() function.
Code Example:
$file = "example.txt"; $content = "Hello, World!"; file_put_contents($file, $content);
This code will write "Hello, World!" to the "example.txt" file. If the file does not exist, it will be created; if it already exists, its contents will be overwritten.
If you want to append content to an existing file instead of overwriting it, you can use fopen() with the "a" flag and then write with fwrite(). Here's an example:
Code Example:
$file = "example.txt"; $content = "Hello, World!"; if ($handle = fopen($file, 'a')) { fwrite($handle, $content); fclose($handle); }
This code will append "Hello, World!" to the end of the "example.txt" file.
PHP provides the rename() function to rename a file. Here's an example:
Code Example:
$oldFile = "example.txt"; $newFile = "new_example.txt"; rename($oldFile, $newFile);
This code will rename the "example.txt" file to "new_example.txt".
To move a file from one location to another, you can also use the rename() function. Here’s an example:
Code Example:
$sourceFile = "example.txt"; $destinationFolder = "uploads/"; $destinationFile = $destinationFolder . $sourceFile; rename($sourceFile, $destinationFile);
This code will move the "example.txt" file to the "uploads" folder.
This article has provided a detailed introduction to PHP file read/write operations, covering file reading, writing, appending, and moving. By utilizing these functions, developers can handle files more flexibly to meet various development needs. We hope this article helps you better understand and use PHP file operations.