Php File Handling

fopen(): This function is used to open an existing file or create new according to need.

It takes two arguments:-

ArgumentsDescription
NameFile name
ModeIt specifies operations to perform.
1 - r:- It opens file at read mode. It checks file exist or not if exist then open file. File pointer at beginning.
2 - r+ :- read then write. It is same as read mode.
3 - w :- It opens file at write mode. It checks file exist or not. If file exist then open file. Otherwise create file. File pointer at beginning. When we open file at write mode the interpreter truncate file, it means delete file temporarily and re-create.
4 - w+ :- Write then read. It is same as write mode.
5 - a :- This is append mode. In append mode file pointer at the end of file. It adds new data into file.
6 - a++ :- Write the read. It is same as append mode.

fwrite() :- It is used for writing data into file. It takes three arguments.

ArgumentsDescription
streamA file system pointer resource that is typically created using fopen().
dataThe string that is to be written.
lengthIf length is an int, writing will stop after length bytes have been written or the end of data is reached, whichever comes first.

Example of fwrite()

<?php
$f = fopen("demo.txt", "w");
if($f == null) {
    die("file not exists");
}
$a = fwrite($f, "This is first example of file.");
if($a) {
    echo 'Data added';
}
else {
    echo 'Data not added';
}
?>

fread() :- It is used for reading data from file. It takes two arguments.

ArgumentsDescription
streamA file system pointer resource that is typically created using fopen().
lengthUp to length number of bytes read.

Example of fread()

<?php
$file = "demo.txt";
$f = fopen($file, "r");
if($f == null) {
    die("file not exists");
}
$fs = filesize($file);
$data = fread($f, $fs);
echo $data;
?>

Example of fopen with a mode

<?php
$f = fopen("demo.txt", "a");
if($f == null) {
    die("file not exists");
}
$a = fwrite($f, "Php class");
if($a) {
    echo 'Data added';
}
else {
    echo 'Data not added';
}
?>

×
Google login
SignUp with Email
X