将file_put_contents文件存储在安全位置

Currently, I'm connecting to a database using the following:

    <?php

    try
    {
        $dbh = new PDO(
            'mysql:host=localhost;port=3306;dbname=databaseName',
            'databaseUser',
            'databaseUserPassword');

        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    }
    catch(PDOException $e)
    {
        echo "I'm sorry, Dave. I'm afraid I can't do that.";
        file_put_contents('PDOErrors.txt', "
" . $e->getMessage(), FILE_APPEND | LOCK_EX);
    }

    ?>

This writes the text file to the same location of this PHP file, which is publicly available on my website. While this location isn't explicitly disclosed to the user, if someone found this location (i.e. example.com/PDOErrors.txt) then they would be able to view the contents of that file just fine.

My question(s): is this the correct way to handle this? Can I password protect the directory? Can I write this file somewhere outside of the website that isn't publicly available (like the root folder above the website)?

I need to be able to access the PHP file to access my database (I'm doing this inside of a game for leaderboard type stuff) but the output file should only be available to me.

A good way to do that is to put everything that should not be accessible from outside in a folder which can't be reached.

For example you have that structure:

/nameofproject
  - /data
    - /logs
  - /library
  - /public
    - index.php <- www.example.com would point to this

Then you would have to configure your vhost and your .htaccess. You could look at Symfony 2 or Zend Framework 2 how they did that.

.htacces code for your protected folder:

order deny,allow
deny from all