Let’s see the reading and writing to files in PHP with the help of an Example.
Create a text file example “file.txt” in the root folder.
//reading the contect
$stockFile = "file.txt";
$fh = fopen($stockFile, 'r');
$stockfileContents = fread($fh, 21); fclose($fh);
You can open the file using “fopen” command
The “fread” command is for reading the content of file
//writing
if(isset($_POST['update'])){
if(!empty($_POST['filename'])){
$stockFilew = "file.txt";
$stockFilew2 = fopen($stockFilew, 'w+') or die("Can't open file.");
$newContents = $_POST['filename'];
fwrite($stockFilew2, $newContents);
fclose($stockFilew2);
}
}
Here “fopen and fwrite” is for opening the file and write operation. The fclose for close the file.