How to read and write in files using PHP

In this article, we will learn how to read and write in the file.

There are 3 simple steps to do file operation :

  1. Open a file in the proper mode.
  2. Read/write contents in file.
  3. Close the file.

Modes of opening a file in PHP

There are several ways to open a file:

  • w: It opens the file in write-only mode. If the file is not present, a file is created. If the file exists, then the contents of the file are erased.
  • r: It opens¬†the file in read-only mode.
  • a: It opens the file in append mode i.e. the contents are inserted at the end of the file.
  • w+: It opens the file in read and write mode. If the file is not present, a file is created. If the file exists, then the contents of the file are erased.
  • r+: It opens the file in read/write mode.
  • a+: It opens the file in read/write mode. The contents are inserted at the end of the file.

Opening a file in PHP

The function to open a file:

fopen(filename,mode);

Example:-

fopen("myfile.txt",'w');

Reading a file in PHP

The fread() function is used to read the contents of a file.



Example:-

<?php

$file = "myfile.txt";

//opening a file in reading mode
$h = fopen($file, 'r');

//reading file upto file length and storing it in a variable "fcontents"
$fContents = fread($h, filesize($file));

//closing file
fclose($h);

//displaying the content
echo $fContents;

?>

Output:-

Welcome to codespeedy.This is a example of file read.

Writing a file in PHP

The fwrite() function is used to write contents to a file.

Example:-

<?php

$file = "myfile.txt";

//opening a file in writing mode
$h = fopen($file, 'a');

//adding new contents to file
$ncontents = "This line added to the file.";
fwrite($h, $ncontents);

//closing file
fclose($h);

//opening a file in reading mode
$h = fopen($file, 'r');

//reading file to check whether content is added or not
$fContents = fread($h, filesize($file));

//closing file
fclose($h);

//displaying the content
echo $fContents;

?>

Output:-

Welcome to codespeedy.This is a example of file read. This line added to the file.

Closing a file in PHP

The following function is used to close an opened file:

fclose(filename);

Example:-

fclose($file);

This is how we can perform read and write operations on a file.

If you have any doubts on the above topic, please put a comment below:

See also,

Leave a Reply

Your email address will not be published. Required fields are marked *