
File handling functions are an essential part of any coding language. PHP has a collection of functions to read and to files too. We can use them to create, edit, delete, move, check the existence of and upload files. That’s pretty much everything you can do with files, except using them in a script helps you automate those tasks.
Prerequisites
Like always I assume that you know the basics of php. For instance if you can understand what this
$variable=”value”;
if($variable==”value”)echo “Variable has a value”;
means, we’re good to go.
How does php treat files?
There isn’t any huge difference between how we open and read files and how php does it. Every file has data, in simple words they’re all text, even the image and video files, only unreadable text. What do we do when we need to read or write into a file. We open it and do our thing. That’s just the way php does it too. No extra complications except for some code. You’ll understand it as soon as we do some coding.
Read files

Reading a file in php can be done using a number of function. We can group them on the ease of use. So there are easy and hard ways to open and read a file. Lets look at the easy functions first.

Easy ways or functions to read a file
Location of the file
Its important that you specify the right location of the file you want to read. So if the file’s in the same directory as the script the location should be the filename, but if its in the parent directory if the script the location would be ../filename. And if the file’s located in a sub directory of the folder that script is in location is subdirectory/filename.
1. file()
file() reads a file and copies it into an array on a line by line basis, each line is treated as one value of the array.
Here’s how you use it.
$text=file($fileName)
If the contents of the file would have been like this.
First line
Second line
Third line
The array would be the same as.
$text[1]=”First line”;
$text[2]=”Second line” and so on.
2. file_get_contents()
This one’s pretty much like file() too. The only difference is that it reads the contents of the file into a string. No arrays.
$text=file_get_contents($fileName);
If the contents in the text file are the same as in the first function, the value of the $text variable would be like.
$text= “First line \n Second line \n Third line \n”;
3. readfile()
This ones a very much different from the other two in the manner it deals with the output. It reads the file and displays it on the screen. For example.
readfile($fileName);
Would output “First line \n Second line \n Third line\n” on to the screen. You cannot store it in a variable.
The little hard way, my way
Remember I told you about php opening the file before reading or writing to it, well.
Meet the big guy fopen(), file opener function.

It does exactly what its name suggests, opens a file to read or write. Now you might be thinking, why open a file where as we can use the easy functions like read or file_get_contents. You’ll have the reason soon, lets see how far the rabbit hole goes.
Something about fopen
But before we continue, fopen unlike all the functions above, takes two arguments.
fopen($fileName, $mode);
The first one as we can see is the filename, but the second one seems a little new. Mode tells fopen the reason we’re opening the file for. See? fopen can be used to open a file for both reading and writing. So if we’re opening the file to read we should specify “r”, the first character in read as mode and if we’re opening it to write we specify “w” as mode. Isn’t that convenient?
Keep in mind that.
“r” is the mode to read
“w” is to write
Alright lets open up the file to read.
$text=fopen($fileName,”r”);
Go ahead, you should try this, chose any text file and open it using fopen().
Lets echo the output now.
echo $text;
Did you see something like this Resource id # some number? What happened there? Well don’t worry its supposed to happen. Using fopen alone doesn’t read a file, it just opens a file for reading. The variable that uses fopen turns into a file handle.
File handle
Lets think of file as a room or a file cabinet. What you we do to see what’s in the room or file cabinet? We open it using our hands
. File handles are the hands that open the file. They open the file and keep them open till we close them. That makes sense. Doesn’t it?
So $fileHandle=fopen($fileName,”r”);
1. Use fread to read the fopen’ed file
Ok, so fread here’s the function we use to read the opened file. We’ll use fwrite if we need to write, but we’ll discuss it later. This is how we make it read the fopen’ed file. fread has two arguments too damn.
$text=fread($fileHandle, $howMuchWeWantToRead);
$fileHandle’s an important thing here. We must always provide an fopen’d file handle to fread as its first argument. Its our file opening hand
. fread cannot read a file that’s not opened. The other weird argument $howMuchWeWantToRead like the name suggests read the amount of data we specify in bytes we need it to read. It provides more control over reading the file. If we want it to read the whole file we need to provide it with the full size of the file in bytes. But how to we do that.
filesize() to the rescue

filesize is a very useful function. It provides us with the size of a file in bytes. There are a lot of other uses too. This is how its used.
$size=filesize($fileName);
$size will have the size of the file in bytes. So till now our file reading code should look like this.
$fileHandle=fopen($fileName,”r”);
$size=filesize($fileName);
$text=fread($fileHandle,$size);
Try echo’ing $text now.
echo $text;
Aha, the file has been read and output ed.
Quite a lot of work to open and read a file you might think. But the easy functions do it too, it just does it automatically. Doing it like this helps us know how things work and provides us with more control.
2. fgets
Don’t worry, its the same as fread, use it in case you get bored of fread or need a shorter named function like it. But it has one difference. You don’t need to specify the size of how much you want it to read, it just reads a whole line or till it reaches the end of a line if you don’t specify the length of how much to read. This is how we use it.
$text=fgets($fileHandle,$length[optional]);
You can also use it like this if you don’t wanna specify the size of the file but need to read the whole file.
$text=”;
while(!feof($fileHandle)){
$line=fgets($fileHandle,100);
$text.=$line;
}
echo $text;
Yea, you must have seen the new function feof up there. Its a simple function that checks if the pointer has reached the end of the file. Ah whats a pointer then? Well lets talk about opening a book to read, in order to finish reading it we need to read it line by line till we reach the end. Pointer’s the thing than helps the fileHandle move from line to line. Still not clear? Pointer’s and fileHandles are to the script as our eyes and hands are to us
. When each loop finishes and each fgets reads the pointer moves further just like us turning pages. I know it sounds weird. But it’ll make sense soon.
feof()
feof’s a function that check’s if the pointer has reached the end of the file. This is how we use it.
feof($fileHandle);
You can use the same method with fread too. Just replace the fgets with fread.
There are a few more functions too, but we’ll just stick to the basic ones for now.
Now that we’ve done some extensive reading on reading files with php lets do some more reading on writing files with php, yay
.
Write to files

This section’s going to be pretty short since we’ve covered all the basics up there. And like before we have the easy and hard ways and functions to write to a file.
The easy ways
1. file_put_contents
file_put_contents just like file_get_contents with the exception that we use it to write to a file. It takes three arguments. Two necessary and one optional. Here’s how we use it.
file_put_contents($fileName,$data,$option);
It takes a filename and writes $data to it, if the file doesn’t exist it creates it, pretty easy to understand. But the issue is that it overwrites the data in the file if it already exists. That’s when the third argument comes into play. It helps us set optional flag if we don’t want it to overwrite the file. So if we don’t want it to overwrite the data in an already existing file we set FILE_APPEND as the third argument. In this case it just appends the data on top of the existing ones. For example. If the file has data “old data” in it the new data will be appended to it and the file will look like “old data \n new data” now.You can also use the flag or option LOCK_EX which locks the file so that no one else writes to it while we do.
The little hard ways
1. fwrite

fwrite works almost the same as fread, the only difference is that it writes instead of reading and like file_put_contents creates a new file if the file doesn’t exists and appends or overwrites the data in the existing file depending on the mode you specify. This is how we can use it.
fwrite($fileHandle,$data,$maximumAmountOfDataAllowedToBeWritten);
The third argument is optional and is like a safety feature so that we don’t write more data in case we have a limit to write to the file. But you won’t be using it mostly.
Some modes for fopen’ ing a file
‘w’ Open a file to write. Create it if it doesn’t exist.
‘r’ Open a file to read.
‘w+ Open a file to read and write, attempt to create it if it doesn’t exist
‘r+’ Open a file to read and write
‘a’ Open a file in the append mode or don’t overwrite mode
. Create it if it doesn’t exist.
‘a+’ Open a file in read and append mode. Create if it doesn’t exist.
2. fputs
Same as fwrite.
So that covers the basics of reading and writing files in PHP. Hope it was of some use.
Oh and always fclose what you fopen

PHP may not close the file if it ends prematurely. So its important that we close the file using fclose function, you know just to be safe or it may remained opened
.
fclose($fileHandle);
This is how we fclose a file. Its not necessary to do this, but its a good coding habit.
![]()
Other file handling functions
unlink($fileName)
Deletes the file.
chmod($fileName,$perm)
Changes the permissions on a file.
chown($fileName,$user)
Changes the ownership of a file to $user.
copy($originalFile, $copyFile)
Makes a copy of a file in the destination provided as the first argument to the destination provided in the second argument.
file_exists($pathToTheFile)
Checks if a file exists and returns true or false depending on its existence.
mkdir($dirName,$perm[optional])
Creates a directory of the name $dirName with permission $perm if its specified.
rmdir($dirName)
Removes or deletes an empty directory.If the directory isn’t empty we’ll have to delete all the files in it.
link($fileName,$shortCut)
Creates a link or shortcut to the $fileName in the location or file specified in $shortCut.
basename($fullPathToTheFile, $suffix[optional]):
Given the full path to a file, this function will return the basename or name of the file. Its not much of a use, but who know, we might need it some day.
$name=baseName(“/path/to/file.php”);
//Returns file.php
$name=basename(“path/to/file.php”,”.php”);
//Returns file










