Detailed explanation and examples of PHP file read and write operations
1. Introduction
In the development process, it is often necessary to read and write files, such as reading configurations file, log file, etc., or write data to a file. PHP provides a wealth of file reading and writing functions. This article will introduce PHP's file reading and writing operations in detail and give some practical examples.
2. File reading operation
Code example:
$file = "example.txt"; $content = file_get_contents($file); echo $content;
The above code will read the contents of the file named example.txt and output it to the page.
Code example:
$file = "example.txt"; if ($handle = fopen($file, 'r')) { while (!feof($handle)) { $line = fgets($handle); echo $line."
"; } fclose($handle); }
The above code will read the contents of the example.txt file line by line and output it to the page. Each line will be wrapped with the br tag. .
3. File writing operation
Code example:
$file = "example.txt"; $content = "Hello, World!"; file_put_contents($file, $content);
The above code will write "Hello, World!" to a file named example.txt. If the file does not exist, it will be created automatically; if the file already exists, the original content will be overwritten.
Code example:
$file = "example.txt"; $content = "Hello, World!"; if ($handle = fopen($file, 'a')) { fwrite($handle, $content); fclose($handle); }
The above code will append "Hello, World!" to the end of the example.txt file.
4. File moving operation
Code example:
$oldFile = "example.txt"; $newFile = "new_example.txt"; rename($oldFile, $newFile);
The above code will rename the example.txt file to new_example.txt.
Code example:
$sourceFile = "example.txt"; $destinationFolder = "uploads/"; $destinationFile = $destinationFolder . $sourceFile; rename($sourceFile, $destinationFile);
The above code moves the example.txt file to the uploads folder.
5. Summary
This article introduces in detail the relevant knowledge and examples of PHP file read and write operations, including file reading, file writing, file movement and other operations. By using these functions, we can operate files more flexibly to meet the needs of the development process. I hope this article will help you gain an in-depth understanding of and use PHP file reading and writing operations.
The above is the detailed content of Detailed explanation and examples of PHP file reading and writing operations. For more information, please follow other related articles on the PHP Chinese website!