Skip to main content

File Handling in PHP Tutorial

For any PHP programmer or web developer performing file operation is one of most frequent task. Because files contains data  and web development is all about manipulation of data. But one of the most common problems with the developer are the file handling code written on one environment create issue on other environment. In this tutorial we will explore various aspect of file handling in php. We will explore from basic beginning steps of creating file to some advance aspect like permission, file attribute etc.
File Handling in PHP

What is file handling in PHP

To understand file handling one should know what is file? File is nothing but a sequence of bytes stored in a group. We create file to store information permanently in our system. With file we not only permanently store the information but also perform some operation like read, edit, delete, move etc. These operation performed on the file is called file handling.

Every programming provides a way to perform file handling. Like other programming language PHP also provides some set of methods for file handling. Later part of this tutorial we will explore various functions for file handling in PHP. Some people also uses term File I/O for file handling.

File handling  activity in PHP can be broadly classified in following category

  1. Opening & Closing File
  2. Creating File
  3. Reading File
  4. Writing File
  5. Editing File

For all above activity let us explore how to do via PHP script.

Opening & Closing a File

Before doing any activity of file handling in php, first we need to open the file. Because once you will open the file you will get your file file pointer to perform any further operation on the same file. Also while opening the file you can provide information about mode in which you want to open. Mode will be like read, write etc.

In PHP we can open file using php function fopen. fopen accepts following parameters as mandatory:

  1. Location of the File : This is mandatory parameter of the fopen fuction. It should be filename with complete path like /var/yourdirctory/yourfile.txt in linux and c:/test/yourfile.txt in windows.
  2. Mode : While opening the file in php you need to provide the mode in which you would like to open the file. Mode also decide where your file pointer will be place. For example if you will open in read or write mode pointer will be at beginning but if you will open for amendment mode pointer will be at end of file. Below are the parameter accepted for the mode in PHP
    1. r : Opens for reading only. Pointer will be at beginning of file.
    2. r+ : Opens for reading and writing both. Pointer will be at beginning of file.
    3. w : Opens for writing only. Pointer will be at beginning of file. If file does not exists the it will try to create file as well.
    4. w+ : Opens for writing and reading both. Pointer will be at beginning of file. If file does not exists the it will try to create file as well.
    5. a : Opening for writing but pointer will be at end. If file does not exists the it will try to create file as well.
    6. a+ : Opening for writing and reading and pointer will be placed at end. If file does not exists the it will try to create file as well.
    7. x : Create and open file for writing. If file will exists then opening will be fail and will throw warning.
    8. x+ : Create and open file for reading and writing both. If file will exists then opening will be fail and will throw warning.

PHP function fopen returns file pointer if file got successfully opened otherwise false.

To close the file pointer php provide function with name fclose. PHP function fclose accepts file pointer as input parameter.

Below are some examples:

Opening file for reading:
$path = dirname(__FILE__).'/test.txt';
$fp = fopen($path, 'r');
if(!$fp){
echo 'file is not open';
}
else
{
echo 'file open';
}
fclose($fp);

$fp is the file pointer return by fopen.
Opening for reading and writing using r+ mode:
$path = dirname(__FILE__).'/test.txt';
$fp = fopen($path, 'r+');
if(!$fp){
echo 'file is not open';
}
else
{
echo 'file opens';
}
fclose($fp);

Opening for writing only with w mode
$path = dirname(__FILE__).'/test.txt';
$fp = fopen($path, 'w');
if(!$fp){
echo 'file is not open';
}
else
{
echo 'file opens';
}
fclose($fp);

Note: If file exists on the location and your file pointer i.e. $fp returns false then it might be possible that your apache user does not have permission to open that file. Also it might be possible that your apache user has permission to read only but you are trying to open in write mode. 

Since in the most of the modes of fopen file pointer comes at beginning or end of the file. We can also move the file pointer to any location inside the file. PHP provide function with name fseek.

Fseek accepts following 2 mandatory parameters:

  1. File Pointer
  2. Location where need to place pointer.

For example:
$path = dirname(__FILE__).'/test.txt';
$fp = fopen($path, 'w');
if(!$fp){
echo 'file is not open';
}
//Do some operation and while operation file pointer moves at 10th characters
fseek($fp, 0);//place pointer at beginning 
fclose($fp);

Reading the file in PHP

To read the file content PHP provides function with name fread. PHP function fread accepts following two parameters:

  1. File Pointer : File pointer returned by the fopen function. This is mandatory parameter.
  2. Length: Number of byte to read.

Following is example to read all content from file:
$path = dirname(__FILE__).'/test.txt';
$fp = fopen($path, 'r');
if(!$fp){
echo 'file is not opend';
}
$contentoffile = fread($fp, filesize($path));
echo $contentoffile;
fclose($fp);

In above code line $contentoffile = fread($fp, filesize($path)); is having two paramter one is $fp which is file pointer. Other parameter is number of byte, because function filesize always give size of file in bytes. Now since pointer is placed at beginning of the file and lenght to read is provided as complete file size so it gives the complete data of the file.

Similarly to read first 10 bytes of the file below is the code:
$path = dirname(__FILE__).'/test.txt';
$fp = fopen($path, 'r');
if(!$fp){
echo 'file is not opend';
}
$contentoffile = fread($fp, 10);
echo $contentoffile;
fclose($fp);

Read 10 bytes after 5 bytes from beginning
$path = dirname(__FILE__).'/test.txt';
$fp = fopen($path, 'r');
if(!$fp){
echo 'file is not opend';
}
fseek($fp, 5);
$contentoffile = fread($fp, 10);
echo $contentoffile;
fclose($fp);

Creating a file in PHP

To create file we only need to fopen the file in one of the following mode as per the requirement:

  1. w
  2. w+
  3. a
  4. a+
  5. x
  6. x+

For example if you need to create a file and simply close then use x.
$path = dirname(__FILE__).'/b.txt';
$fp = fopen($path, 'x');
if(!$fp){
echo 'file is not opend';
}
fclose($fp);

Writing in the file in PHP

PHP provides method with name fwrite to write anything inside the file. PHP function fwrite accepts following parameter:

  1. File Pointer : File pointer from fopen with correct mode for writng file.
  2. Content string : Content which need to write in the file.
  3. Length: Optional paameter, if it is passed then after specified lenth writing will be stoped.

In PHP to write something inside the  file you need to open file in one of the following mode as per your requirement

  1. r+
  2. w
  3. w+
  4. a
  5. a+
  6. x+

For example to create and write text in the file following is the code:
$path = dirname(__FILE__).'/newfile.txt';
$fp = fopen($path, 'w');
if(!$fp){
echo 'file is not opend';
}
fwrite($fp, 'this is simple text written');
fclose($fp);

To write at the end of the file below is the code with fopen with mode a:
$path = dirname(__FILE__).'/newfile.txt';
$fp = fopen($path, 'a');
if(!$fp){
echo 'file is not opend';
}
fwrite($fp, 'this is simple text written');
fclose($fp);

To write at the end of the file and read complete file with a+ mode:
$path = dirname(__FILE__).'/newfile.txt';
$fp = fopen($path, 'a+');
if(!$fp){
echo 'file is not opend';
}
fwrite($fp, 'last word to write');
fseek($fp, 0);
echo fread($fp, filesize($path));
fclose($fp);

 

 

 

Support Me by Sharing This Article

Ankur Kumar Singh

I am a PHP programmer having some knowledge about Linux. I am always interested in web development and knowledge sharing. I am full time tech evangelist part time human being. :-)

Leave a comment/Ask Question

3 thoughts on “File Handling in PHP Tutorial

shares