note 93272 modified in function.fopen by danbrown

From: Date: Tue, 01 Sep 2009 01:18:11 +0000
Subject: note 93272 modified in function.fopen by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-160102@lists.php.net to get a copy of this message
As someone has mentioned already, using fopen() in r+ mode overwrites the beginning of the file with new data. So, if you want to append new data to the beginning of the file, do so as follows: <?php $filename = "myfile.txt"; //first, obtain the data initially present in the text file $ini_handle = fopen($filename, "r"); $ini_contents = fread($ini_handle, filesize($filename)); fclose($ini_handle); //done obtaining initially present data //write new data to the file, along with the old data $handle = fopen($filename, "w+"); $writestring = "text to write to file\n" . $ini_contents; if (fwrite($handle, $writestring) === false) { echo "Cannot write to text file. <br />"; } fclose($handle); ?> --was-- The correction to my last post is that the old data needs to be added to the end of the new data.. Corrected below... As someone has mentioned already, using fopen() in r+ mode overwrites the beginning of the file with new data. So, if you want to append new data to the beginning of the file, do so as follows: <?php $filename = "myfile.txt"; //first, obtain the data initially present in the text file $ini_handle = fopen($filename, "r"); $ini_contents = fread($ini_handle, filesize($filename)); fclose($ini_handle); //done obtaining initially present data //write new data to the file, along with the old data $handle = fopen($filename, "w+"); $writestring = "text to write to file\n" . $ini_contents; if (fwrite($handle, $writestring) === false) { echo "Cannot write to text file. <br />"; } fclose($handle); ?> http://php.net/manual/en/function.fopen.php

« previous php.notes (#160102) next »