I tried to use fopen, but I only managed to append content to end of file. Is it possible to overwrite all contents with new content in PHP?
Example 1: Using the open() method to overwrite a file. To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it. We have a new file with the name “myFile. txt”.
$fh = fopen( 'filelist. txt', 'w' ); fclose($fh); In clear. php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER'] value.
The PHP fwrite() function is used to write and append data into file. fwrite($fp, ' this is additional text '); fwrite($fp, 'appending data');
The file_put_contents() writes data to a file. This function follows these rules when accessing a file: If FILE_USE_INCLUDE_PATH is set, check the include path for a copy of filename. Create the file if it does not exist. Open the file.
Use file_put_contents()
file_put_contents('file.txt', 'bar'); echo file_get_contents('file.txt'); // bar file_put_contents('file.txt', 'foo'); echo file_get_contents('file.txt'); // foo
Alternatively, if you're stuck with fopen()
you can use the w
or w+
modes:
'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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With