PHP File Handling
PHP can create, read, write and delete files on the server. This is useful for logs, uploaded files, text data and CSV files. In this chapter you will learn the two ways to work with files: the easy functions, and the file handle functions.
The easy way: read and write a whole file
<?php
$file = "sample.txt";
// Write (creates the file, or replaces the old content)
file_put_contents($file, "Line 1\nLine 2\n");
// Add text at the end
file_put_contents($file, "Line 3\n", FILE_APPEND);
// Read the whole file
echo nl2br(file_get_contents($file));
?>
Output:
Tutorials Class - Output Window
Line 1
Line 2
Line 3
file_get_contents() returns the whole content as a string. file() returns an array with one item for each line.
<?php
$lines = file("sample.txt", FILE_IGNORE_NEW_LINES);
echo count($lines) . " lines<br>";
echo $lines[1];
?>
Output:
Tutorials Class - Output Window
3 lines
Line 2
The file handle way: fopen()
For big files or when you need more control, open the file with fopen(). The second parameter is the mode.
| Mode | Meaning |
|---|---|
| r | Read only. The file must exist |
| r+ | Read and write |
| w | Write only. Creates the file, or erases the old content |
| a | Write at the end (append). Creates the file if needed |
| x | Create a new file for writing. Fails if it already exists |
<?php
$handle = fopen("sample.txt", "r");
if ($handle === false) {
die("Could not open the file.");
}
while (($line = fgets($handle)) !== false) {
echo htmlspecialchars(trim($line)) . "<br>";
}
fclose($handle);
?>
Output:
Tutorials Class - Output Window
Line 1
Line 2
Line 3
fgets()reads one line at a time, so it uses little memory.fwrite()writes text to an open file.- Always close the file with
fclose().
Check, size and delete a file
- Check if a file exists: file_exists().
- Get the size: filesize().
- Delete a file:
unlink(). See unlink() vs unset(). - Create a folder with
mkdir()and delete it withrmdir().
<?php
$file = "sample.txt";
if (file_exists($file)) {
unlink($file);
echo "File deleted";
}
?>
Output:
Tutorials Class - Output Window
File deleted
Safety tips
- Check if
fopen()orfile_get_contents()returnedfalse. - Never build a file path from user input without checking it. A user can send
../../to reach other files. - The folder must have write permission for PHP.
- When many users write the same file at the same time, use
flock()to lock it.
Related: PHP File Upload and PHP File Inclusion.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| No Content Found. |