Working with files is an essential part of web development, as you often need to read and write data to and from files on the server. In this lesson, we'll cover the basics of file input and output in PHP, including reading, writing, and modifying files.
PHP provides the fopen()
function to open a file and return a file handle resource. You must specify the file mode, which indicates how you intend to use the file (e.g., read, write, or append).
$file = fopen("example.txt", "r"); // Open the file for reading
fclose($file); // Close the file when done
fgets()
: Reads a line from the file.$file = fopen("example.txt", "r");
while (($line = fgets($file)) !== false) {
echo $line . "<br>";
}
fclose($file);
fread()
: Reads a specified number of bytes from the file.$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt")); // Read the entire file
echo $content;
fclose($file);
file_get_contents()
: Reads the entire contents of a file into a string.$content = file_get_contents("example.txt");
echo $content;
fwrite()
: Writes a string to the file.$file = fopen("example.txt", "w");
fwrite($file, "This is a test."); // Write a string to the file
fclose($file);
file_put_contents()
: Writes a string to the file, creating the file if it does not exist.file_put_contents("example.txt", "This is a test.");