PHP | File Handling

Last Updated On Sunday 27th Mar 2022

Basics of File Handling

File handling in PHP is similar as file handling is done by using any programming language like C.

Checking Whether a File Exists

To determine whether a file already exists, you can use the file_exists function,
which returns either TRUE or FALSE and is used like this

	if (file_exists("testfile.txt")) echo "File exists";

Creating a File

At this point, testfile.txt doesn’t exist, so let’s create it an write.

	<?php // testfile.php
($fh = fopen("testfile.txt", "w")) or die("Failed to create file");
$text = <<<_END
Line 1
Line 2
Line 3
fwrite($fh, $text) or die("Could not write to file");
echo "File 'testfile.txt' written successfully";

file handling functions in php

Always start by opening the file. You do this through a call to fopen.

fwrite to write to the file (fwrite).

You can also read from an existing file (fread or fgets) and do other things.

  • Finish by closing the file (fclose).You should clean up by closing the file when you’re finished.

Reading from Files

The easiest way to read from a text file is to grab a whole line through fgets.

Reading a file with fgets

($fh = fopen("testfile.txt", "r")) or
    die("File does not exist or you lack permission to open it");
$line = fgets($fh);
echo $line;

Reading a file with fread

($fh = fopen("testfile.txt", "r")) or
    die("File does not exist or you lack permission to open it");
$text = fread($fh, 3);
echo $text;

The fread function is commonly used with binary data.

Copying Files

  • PHP copy function to create a clone of testfile.txt
 copy('testfile.txt', 'testfile2.txt') or die("Could not copy file");
 echo "File successfully copied to 'testfile2.txt'";

Moving a File

To move a file, rename it with the rename function

 if (!rename('testfile2.txt', ''))
 echo "Could not rename file";
 else echo "File successfully renamed to ''";

You can use the rename function on directories, too.

Deleting a File

Deleting a file is just a matter of using the unlink function to remove it from the file‐system.

 if (!unlink('')) echo "Could not delete file";
 else echo "File '' successfully deleted";