I use file_put_contents for that.
For example,
file_put_contents('file.txt', 'Yogesh');
echo file_get_contents('file.txt'); // Yogesh
file_put_contents('file.txt', 'Chauhan');
echo file_get_contents('file.txt'); // Chauhan
I have tried to do the same with fopen() and w+ mode as well. That works pretty well too.
- 'w' -> Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
- 'w+'-> Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
Checkout on PHP manual:
https://www.php.net/manual/en/function.fopen.php
file overwrite