Learn how to Open a file and edit a file in PHP!

Learn how to open an existing file and edit the file using PHP function.

DOWNLOAD THE SCRIPT AT THE BOTTOM

fopen() is the function which help us to read, write and append text file.

fopen(‘filename.txt’, ‘r’) – allows to read / open file

fopen(‘filename.txt’, ‘w’) – allows to read / open file and write in the file

fopen(‘filename.txt’, ‘a’) – allows to read / open file and append in the file

 

fgets() – is a function which is used to read the file line by line.

feof() – is a function used to check whether the pointer reached the end of file.

fwrite() – is a function used to write in a file
In the below example ‘test.txt’ file is used. You need to have a file test.txt file in your folder with some text in it. Or otherwise download the entire script down below!


<?php

$filename = 'test.txt';

//check if file is availble or not
if(file_exists($filename)){

//reading a file
if(isset($_POST['read'])){
$handle = fopen($filename, 'r') or die('Cannot open file: '.$filename);
while (!feof($handle)) {
$contents = fgets($handle, filesize($filename));
echo $contents."<br />";
}
}

//writing in a file
if(isset($_POST['write'])){

$data = $_POST['textboard'];
if($data != ''){
$handle = fopen($filename, 'w') or die('Cannot open file: '.$filename);
fwrite($handle, $data);
} else {
echo "Please Write something on the text box and see";
}
}
}
else{
echo "file is not availble";
}
?>

<html>
<head>
</head>
<body>
<form action="" method="post">
<br /><br /><br />
1. Read File
<input type="submit" name="read" value="Read Existing File" />

<br /><br />

2. Write File

<textarea name="textboard"></textarea>
<input type="submit" name="write" value="Write to File" />

<br /><br />

3. Now Read the File with the text You have written and submitted
<input type="submit" name="read" value="Read Existing File" />

</form>
</body>
</html>

DemoDownload

Leave a Reply

Theme: Overlay by Kaira
Agurchand