Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I overwrite file contents with new content in PHP?

Tags:

file

php

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?

like image 669
newbie Avatar asked Sep 26 '11 06:09

newbie


People also ask

Which mode of the file is used to overwrite the existing contents by the new contents?

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”.

How do you clear the contents of a file in PHP?

$fh = fopen( 'filelist. txt', 'w' ); fclose($fh); In clear. php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER'] value.

Which constant is used to add data in existing file in PHP?

The PHP fwrite() function is used to write and append data into file. fwrite($fp, ' this is additional text '); fwrite($fp, 'appending data');

What is file_put_contents?

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.


1 Answers

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.

like image 83
Mike B Avatar answered Oct 11 '22 19:10

Mike B