Sunday, June 21, 2015

File Read and Write in PHP


Hello guys, how are you?

Today we will look in to the File Operations in PHP.

Whether to read or a write to a file, first of all we must open the file using PHP. The function that we use to open a file in PHP is fopen() function. This function accepts two parameters:-

  • file path
  • the mode that the file should be opened
$fp = fopen("input.txt", "r");

Here file is opened and assigned to a variable. This variable is usually called as file pointer. This will make our operations easy.



Modes that we can open a file :-
  • r - read only
  • w - write only(existing data will be re-written)
  • a - write only(new text will be added to the end of the existing text)
  • x - creates a new file for write only
  • r+ - opens a file for read and write
  • w+ - opens a file for read and write
  • a+ - opens a file for read and write
  • x+ - creates a new file for read and write

After opening the file in read  mode we can read the text which is existing in the file and assign it to a PHP variable. To do that we can use fread()  function. This function accepts two parameters.
  • file path
  • maximum bytes to read
$content = fread("input.txt",1024);

Or else we can use the file pointer variable as parameter. If we use that as a parameter it will read the file till it reach the end of the file.

$content = fread($fp);

If we want to read a single line of the file we can do it using fgets() function. This function also accepts two parameters. 
  • file path
  • file open mode
$content = fgets("input.txt","r");
$content = fread($fp);

In some context we maybe want to check whether the file pointer has reached the end of the file. So we can do it using feof() function. This function accepts one parameter which is the file pointer variable.

if(feof($fp)){
     echo("End of the file has reached!");
}

After opening a file for reading or writing purpose we have to close the file. Otherwise the file pointer will keep the file open and that will lead for errors and unexpected problems. To close a file we can use fclose() function. This function accepts one parameter which is also the file pointer variable.

fclose($fp);

These are the basic and most used file handling functions in PHP and there are plenty of more functions available to do various tasks.
Below link will show some more functions :-


Past Topics :-
Like us on Facebook:



Comment box is open for your comments, ideas and suggestions!

No comments:

Post a Comment