0

Possible Duplicate:
Need to write at beginning of file with PHP

I am trying to make a log file. But I want to insert data at beginning of file. I have read many solutions but many of them given following solution.

-> Open file in append mode.
-> Copy whole data in a variable.
-> concatenate data with temp variable.
-> Rewrite whole file.

I have visit and read following link. Need to write at beginning of file with PHP

I think this process is time consuming if my log file is around 50 to 85 MB.

Is there any that i can move file pointer at beginning of file and then just insert data save that file ?

I need some optimized way that it can work for me.

Community
  • 1
  • 1
Ritesh Patadiya
  • 119
  • 1
  • 6

2 Answers2

2

No, you can't stick new data at the beginning of a file. Your choices are:

  1. open new file, write new data, then append old file to new file
  2. open original file, copy old data "down" farther into the file, then overwrite the start of the file.

Any reason you need to log things at the start of your file? It's trivial to read only the last part of a file.

Marc B
  • 356,200
  • 43
  • 426
  • 500
0

If file isn't HUGE and also you have ample of memory for PHP.. here, a quick PHP to help you:

$toAdd = 'Text to add in beginning';
$file = '/path/to/your/file';
$temp = file_get_contents($file);
file_put_contents($file, $toAdd . $temp);
Keval Domadia
  • 4,768
  • 1
  • 37
  • 64