How to write to a separate PHP file in plugin settings

I need a way of taking a variable from a plugin’s settings and write it to a small key file located in the plugin’s directory. The entire contents of the key file is this:

<?php
$transaction_key = "npo7d3A0d2hhTYF5w9uo";
?>

I’ve tried to use file_put_contents, but I can’t get it to work. Anyone know how to correctly do this?

Solutions Collecting From Web of "How to write to a separate PHP file in plugin settings"

It is impossible especially if you also need to keep the key in secret. Just use the DB.

Yes it works. You are just not passing the right file path.

    $base = dirname(__FILE__); // That's the directory path
    $filename = 'key.php';
    $fileUrl = $base . '/' . $filename;
    $data = '<?php $transaction_key="'. get_option('option_name') . '"?>';
    file_put_contents($fileUrl, $data);