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.

ModeMeaning
rRead only. The file must exist
r+Read and write
wWrite only. Creates the file, or erases the old content
aWrite at the end (append). Creates the file if needed
xCreate 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

<?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() or file_get_contents() returned false.
  • 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.
Interview Questions & Answers
What is include() function in PHP?
Can we include a file two times in any PHP page?
Which is the PHP function to delete a file from server?
What is fopen function PHP?
What is the difference between unlink() and unset() in PHP?
How to check if a file exists in PHP?
How to get the size of a file in PHP?