File Operations in PHP
- 2020年6月01日
- 技術情報
I will talk about file operations in PHP( handling , read, write etc.). Lets take a look at reading file first.
As an example we have a file called test.txt and if we want to read the contents within the file, can simply do like this.
<?php
echo readfile("test.txt");
//this will out put the contents within the file
?>
But what if we want to handle more than reading a file, we can use fopen
<?php
//we have to open the file first along with the operation mode.
//(r,w,a,x) etc. you can see more detail as below.
// https://www.php.net/manual/en/function.fopen.php
$file = fopen("test.txt", "r") or die("Unable to open file!");
//then we read the file by specifying maximum number of bytes to read
echo fread($file,filesize("test.txt"));
// then simply close the file.
fclose($file);
?>
We can also get the first line in file using fgets
<?php
$file = fopen("test.txt", "r") or die("Unable to open file!");
echo fgets($file);
fclose($file);
?>
We can also use feof
to check whether the file reaches to the end.
<?php
$file = fopen("test.txt", "r") or die("Unable to open file!");
// Output until end-of-file
while(!feof($file)) {
echo fgets($file) . "<br>";
}
fclose($file);
?>
If we want to check whether file exists or not , we can do like this
<?php
echo file_exists("test.txt");
//if exists, it will return 1
?>
By Yuuma.
yuuma at 2020年06月01日 11:00:37