In PHP File System allows us to create file, read file line by line, read file character by character, write file, append file, delete file and close file.
PHP supports following functions to handle files.
In PHP, The fopen() function is used to open a file in read mode or write mode or in both read and write modes. And this function accepts two arguments: $filename and $mode.
Syntax:
fopen(string $filename , string $mode)
The $filename represents the file to be opended and $mode represents the file mode for example read-only, read-write, write-only etc.
The fopen() supports the following modes:
r | - | Read Only |
w | - | Write Only |
a | - | Append |
r+ | - | Read & Write. |
w+ | - | Read & Write. |
<?php
$filename = "E:\\studyglance\\simple.txt";
$fp = fopen($filename, "r");//open file in read mode
?>
In PHP, The fread() function is used to read data of the file. It requires two arguments: file resource and file size.
Syntax:
fread(resource $fp,int $length)
Where $fp represents file pointer that is created by fopen() function. And $length represents length of file (bytes)to be read.
<?php
$filename = "D:\\studyglance\\file.txt";
$fp = fopen($filename, "r");//open file in read mode
$content = fread($fp, filesize($filename));//read file
echo "$content";//printing data of file
fclose($fp);//close file
?>
In PHP, The fwrite() function is used to write the content (string) into file.And It requires two arguments: file resource and data(string)
If the file opened in write(w) mode, the fwrite() function will erase the previous data of the file and writes the new data or If the file opened in append(a) mode, the fwrite() function appends the new data at the end of the previous data.
Syntax:
fwrite(resource $fp,string $data)
Where $fp represents file pointer that is created by fopen() function.And $data represents the data to be written.
☞ If the file opened in write(w) mode :
<?php
$filename = "D:\\studyglance\\file.txt";
$fp = fopen($filename, "w");//open file in write mode
fwrite($fp,'PHP is a Scripting Language');
echo "Data written successfully..";
fclose($fp);//close file
?>
☞ If the file opened in append(a) mode :
<?php
$filename = "D:\\studyglance\\file.txt";
$fp = fopen($filename, "a");//open file in write mode
fwrite($fp,' at server side');
echo "Data appended successfully..";
fclose($fp);//close file
?>
In PHP, The fclose() function is used to close an open file.And It requires one argument i.e. "File Pointer"
Syntax:
fclose(resource $fp)
Where $fp represents file pointer that is created by fopen() function.
<?php
$filename = "D:\\studyglance\\file.txt";
$fp = fopen($filename, "r");//open file in write mode
// To close the file
fclose($fp);
?>
In PHP, The unlink() function is used to delete any file.And It requires one argument i.e. "File Name"
Syntax:
unlink(string $filename)
Where $filename represents name of the file to be remove.
<?php
$status=unlink('file.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>