Q:

How to use fopen() in php?

I am trying to make my code able to log any kind of errors on opening a database. What i am trying to do is , create a .txt file that all the logs will be saved in there in case of error.
What i ve done so far is :
bla bla bla
} catch(PDOException $e) {
        //in case of error , we create a log file with the error
        //$PDOException_file = 'PDOException_file_' . date('Y_m_d-H-i-s') . '.txt' ;
        $PDOException_file =  'PDOException_file' . '.txt' ;
        $fh = fopen($PDOException_file, 'w') or die();
        fwrite($fh, date('Y_m_d-H-i-s') . ' PDOException Error: ' . $e->getMessage() . "\n\n" );
        fclose($fh);
        echo 'Error: ' . $e->getMessage();

        }

What i expected from the code i wrote would be to create one .txt file "PDOException" file and inside get the logs like this :
2013_05_02-12-40-02 PDOException Error: bla bla bla

2013_05_02-12-43-02 PDOException Error: bla bla bla 

2013_05_02-13-45-02 PDOException Error: bla bla bla

That means every time i have an error , open the file , write the error make 2 new lines close the file. Then the next time i get an error , i write to the end of this file the error etc etc.
What happens though is that i rewrite in the beginning of my file on the old data. How can i avoid that?

A:

In your code where you have:
$fh = fopen($PDOException_file, 'w') or die()

You should use:
$fh = fopen($PDOException_file, 'a') or die()

The w open's the file for writing only and places the file pointer at the beginning of the file and truncate the file to zero length (deleting all contents). If the file does not exist, it will attempt to create it. The a will open the file for writing only and place the file pointer at the end of the file. If the file does not exist it will attempt to create it.
You can find more information on fopen() here: http://php.net/manual/en/function.fopen.php

