File handling in PHP is the process of reading from and writing to files on a filesystem. PHP provides several built-in functions for working with files:
-
Opening files: The
fopen()
function is used to open a file for reading or writing. It takes two parameters: the name of the file to open, and the mode in which to open it. For example, to open a file named ‘data.txt’ for reading, you can use the following code:bash$handle = fopen('data.txt', 'r');
This code opens the file in read-only mode, and returns a file handle that can be used to read data from the file.
-
Reading files: Once a file is open, you can use the
fgets()
function to read a line of text from the file, or thefread()
function to read a specified number of bytes. For example, to read the entire contents of a file into a string, you can use the following code:bash$handle = fopen('data.txt', 'r'); $contents = fread($handle, filesize('data.txt')); fclose($handle);
This code reads the entire contents of the file into a string variable, and then closes the file handle using the
fclose()
function. -
Writing files: To write data to a file, you can use the
fwrite()
function, which takes two parameters: the file handle, and the data to write. For example, to write a line of text to a file named ‘output.txt’, you can use the following code:bash$handle = fopen('output.txt', 'w'); fwrite($handle, 'Hello, world!'); fclose($handle);
This code opens the file in write-only mode, writes the text ‘Hello, world!’ to the file, and then closes the file handle.
-
Closing files: Once you are finished reading from or writing to a file, you should close the file handle using the
fclose()
function. This releases any system resources that were used to access the file. For example:perl$handle = fopen('data.txt', 'r'); // read data from file fclose($handle);
This code opens a file for reading, performs some operations on the file, and then closes the file handle.
PHP also provides several other functions for working with files, such as file_get_contents()
and file_put_contents()
for reading and writing entire files at once, and fseek()
and ftell()
for positioning within a file. Additionally, PHP provides functions for working with directories, such as opendir()
, readdir()
, and closedir()
, for reading the contents of a directory.