File handling in php

php gives u facility to read, write, open, close and perform various operation over files.

The function use to open the files in php is fopen().

It contains two parameters. The first determines the name of the file with extension and second parameter determines the mode in which the file should open. Like read, write etc.

Example:- Opening of file using fopen()

$file_open=fopen("myfile.txt","r");

The above code is responsible for opening the text file in readonly mode, means u cannot perform any write operation on this file.

Different modes for opening the file are

  1. r+ (Read/Write. Start Reading Writing from the beginning of the file)
  2. w (Write. Open the file and write over file, if file doesn't exist then also creates the file)
  3. w+ (Read/Write.Open the file and write over file, if file doesn't exist then also creates the file)
  4. a (Append. Open the file and write at the end of the file, if file doesn't exist then also creates the file)
  5. a+ (Append/Read. Preserves the contents of the file by writing at the end of the opened file)
  6. x (Write. Creates the new file. Send error as well as return false if the file has been already created).
  7. x+ (Read/Write. Creates the new file. Send error as well as return false if the file has been already created)

If fopen() function unable to open the file it returns false.

Displaying message if file is not opening

$file_open=fopen("myfile.txt","r") or exit("unable to open the file");

Checking End-Of-File (EOF)

Sometime u doesn't know how many lines the file contains that u want to read, for this you use feof() that checks if the End-Of-File has been reached or not. It is better approach to use this during looping process.

if(feof($file_open))

{

echo "End of file has been reached";

}

Closing of file

$file_open=fopen("myfile.txt","r") or exit("unable to open the file");

fclose($file_open);

Reading data line by line from file

The fgets() function is used to read a single line from opened file.

Example:-

$file_open=fopen("myfile.txt","r") or exit("unable to open the file");

while(!feof($file_open))

{

echo fgets($file_open)."\n";

}

fclose($file_open);

Reading a file Character by Character

The fgetc() function is used to read a single line from opened file.

Example:-

$file_open=fopen("myfile.txt","r") or exit("unable to open the file");

while(!feof($file_open))
{
echo fgetc($file_open)."\n";
}
fclose($file_open);



.txt file

.php file


Output

0 comments: