PHP file handling refers to performing operations such as opening, reading, writing, and modifying files using PHP. The typical workflow includes opening a file, reading its contents, writing data, and closing the file.
You can open a file in PHP using the fopen() function, which returns a file pointer. fopen() requires two parameters: the filename and the mode for opening. Common modes include:
Example code:
$fp = fopen('example.txt', 'r');
You can use fgets() to read a file line by line, or fread() to read a specified number of bytes.
Example:
$fp = fopen('example.txt', 'r');
while (!feof($fp)) {
$line = fgets($fp);
echo $line;
}
fclose($fp);
This code reads the content of example.txt line by line until reaching the end of the file.
Use fwrite() to write data to a file.
Example:
$fp = fopen('example.txt', 'w');
fwrite($fp, "Hello world!");
fclose($fp);
This code writes the string “Hello world!” to example.txt, overwriting any previous content.
After completing file operations, call fclose() to close the file and release resources.
Example:
$fp = fopen('example.txt', 'r');
fclose($fp);
fgets() reads one line from the file pointer and moves the pointer to the start of the next line.
Example:
$fp = fopen('example.txt', 'r');
while (!feof($fp)) {
$line = fgets($fp);
echo $line;
}
fclose($fp);
fread() reads a specified number of bytes from the file pointer and does not automatically move to the next line.
Example:
$fp = fopen('example.txt', 'r');
$content = fread($fp, 1024);
echo $content;
fclose($fp);
This reads the first 1024 bytes from example.txt.
file() reads the entire file into an array where each element represents a line in the file.
Example:
$lines = file('example.txt');
foreach ($lines as $line) {
echo $line;
}
fwrite() writes a specified length of string data to a file.
Example:
$fp = fopen('example.txt', 'w');
fwrite($fp, "Hello world!");
fclose($fp);
file_put_contents() writes a string directly to a file, creating it if it does not exist.
Example:
file_put_contents('example.txt', 'Hello world!');
When reading or writing a file that doesn't exist, you might see a “Warning: fopen(): failed to open stream: No such file or directory” error. Check that the file path is correct and that the file exists.
If you encounter a “Warning: fopen(): failed to open stream: Permission denied” error, it means the current user lacks permission to operate on the file. Adjust file permissions or switch to a user with appropriate access.
This article covered PHP file reading and writing operations, including how to open, read, write, and close files. It also pointed out common errors and practical solutions. Mastering these skills can help improve efficiency in file management during development.