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 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
What’s Interpolation in SCSS (Sass)?SCSSHow to enable GD library support for PHP on windows server?PHPHow to get query string values in JavaScript? (URL Manipulation using URLSearchParams)JavaScriptALTER DATABASE in PostgreSQLPostgresDid you get an error while displaying Special Characters in JavaScript?JavaScriptHow to CREATE TABLE in SQL with and without using Another Table?SQL/MySQLWordPress Plugin: Things to knowWordPressCreate a simple bar chart and column chart using pure CSS gridCSSHow to add Local State to a Class in React?ReactHow to calculate elapsed time in JavaScript?JavaScriptHow to Secure Web or Mobile Browsers?MiscellaneousHTML canvas methodsHTML