0

I have an error system that take the date() and the error and insert it into a file:

$fp = fopen('errorFile.txt', 'a');
$message = "At the time: " . date("Y,m,d\|H:i:s") . " the following error took place: " . $e->getMessage();
fwrite($fp, $message);
fclose($fp);

My problem: for start at the fopen at the second parameter I need the pointer to be at the start and that looked at the manual and I need the parameter to be writing only, put the pointer at the start and not truncate the file to zero length, and the only I found is the parameter 'a' all is good with 'a' except the pointer at the end each time, so if anyone know what parameter can I use, so the pointer at the start and it’s write only and it wont truncate the file to zero length, also I am trying as you see to insert the date and for example: the time here is 18:00 the time was inserted is 15:00.

Pablo Claus
  • 5,886
  • 3
  • 29
  • 38
Aviel Fedida
  • 4,004
  • 9
  • 54
  • 88

2 Answers2

1

You can try this logic

$message = "At the time: " . date("Y,m,d\|H:i:s") . " the following error took place: " . $e->getMessage();

$file = '/path/to/file';

$fileContents = file_get_contents($file);

file_put_contents($file, $message . $fileContents);
Vitalii Zurian
  • 17,858
  • 4
  • 64
  • 81
  • 1
    This *is* the way to go if you really want to - I would recommend though, to use a+ and put it to the end of the file to avoid the overhead for each writing operation to first read the file (which may become large over time). If you want it displayed newset-to-oldest, write a small reading-script that reorders the messages (reading will occur less often that writing i suppose) - or use `tail` on the console. – MiDo Jul 30 '12 at 15:43
  • @MiDo you're probably right. I didn't think about performance for this scratch – Vitalii Zurian Jul 30 '12 at 15:44
1

To get you pointer at beginning you need to use fseek function like:

fseek($fp, 0);//place pointer at beginning 

After fseek you can write into file using fwrite

$fp = fopen('errorFile.txt', 'a');
$message = "At the time: " . date("Y,m,d\|H:i:s") . " the following error took place: " . $e->getMessage();
 fseek($fp, 0);
fwrite($fp, $message);
fclose($fp);

For more detail about fseek you can refer to PHP documentation

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343