Forum Moderators: coopster

Message Too Old, No Replies

fopen and write in a file

How to write at the top of a file without deleting content

         

Maleville

4:48 pm on Mar 6, 2004 (gmt 0)

10+ Year Member



Hello.

I write at the top of a file with this:

$fp = fopen($filename,'r+');
fwrite($fp,"my stuff\n");
fclose($fp);

The problem is that it's overwritting the first line of the file.
How to move all the file downward for each access to leave an empty line and write in it.

Birdman

4:58 pm on Mar 6, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I recently went throught the same problem while writing a PHP spider trap. I solved it by first reading the file contents into a variable and then adding it to the new content.

$filename = "/path/to/file/";
$newcontent = "My new content here \r\n";

$handle = fopen($filename, 'r');
$newcontent .= fread($handle,filesize($filename)); // add old content to new
fclose($handle);

$handle = fopen($filename, 'w+');
fwrite($handle, $newcontent.$oldcontent,strlen($newcontent));
fclose($handle);

Maleville

9:27 am on Mar 7, 2004 (gmt 0)

10+ Year Member



Thank you very much Birdman, you saved my life and WebmasterWorld is the best forum in the world as members and moderators (I think to jdMorgan) answer with clear and real content.

It's funny, because I work too on a badbot trap (with your code it is now finished).
If you want we can exchange our views on this subject.

Maleville

5:50 pm on Mar 21, 2004 (gmt 0)

10+ Year Member



I'm sorry Birdman, but where/what is $oldcontent?

<?
$datum = date("d-m-Y (D) H:i:s",$tmestamp);
//
$filename = "./.htaccess";
# IP in regex
$remaddr = $REMOTE_ADDR;
$remaddr = preg_quote ($remaddr, "/");
// New line
$newcontent = "SetEnvIf Remote_Addr ^".$remaddr."$ ban # $datum\r\n";
$handle = fopen($filename, 'r');
$newcontent .= fread($handle,filesize($filename));
fclose($handle);
// Open and write new content in .htaccess (CHMOD 644)
$handle = fopen($filename, 'w+');
fwrite($handle, $newcontent.$oldcontent,strlen($newcontent));
fclose($handle);
?>