Yogesh Chauhan's Blog

How to overwrite file contents with new content in PHP?

in PHP on February 20, 2020

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


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
10 Usability Blunders to AvoidUI/UXHow to create a Recent Posts function in WordPress?WordPressRecursion in JavaScriptJavaScriptWhy do we need HAVING Clause in SQL?SQL/MySQLHow to create Flickering Texts using CSS?CSSHow to remove the Gutenberg Block Library CSS from WordPress?WordPressHow to get current timestamp in Swift 4 and 5?SwiftALTER DATABASE in PostgreSQLPostgresShort-Circuit Evaluation in JavaScriptJavaScriptHow to create a simple drop down menu using JavaScript and CSS?CSSWhat are “holes” in a React component?ReactWhat’s a Closure in JavaScript?JavaScript