File Operations in PHP

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.



アプリ関連ニュース

お問い合わせはこちら

お問い合わせ・ご相談はお電話、またはお問い合わせフォームよりお受け付けいたしております。

tel. 06-6454-8833(平日 10:00~17:00)

お問い合わせフォーム