Haven’t blogged for a while. So much for Scribefire helping it happen. Oh well. Discovered something interesting this morning so thought I’d stick it here. It’s probably well known among PHP gurus but hey, worth sharing anyway, right?
So I am writing an upgrade to my web app, and as part of the upgrade many of the config variables have changed. For the record, I put them all into an array… so before they were things like $db_host, $db_pass, now they have become $config['db_host'], $config['db_pass'] – this way in my classes and functions I only need to declare one global variable at the start and they have access to the whole gamut they need. But I’m writing a script to try and do the upgrade seamlessly in one step and it becomes problematic – I need to access all the old variables in the old config file, then rewrite a new config file with the new variables (and remove the old ones).
Never fear – it is possible in PHP to write to a file even if you have already included it. I did a quick google to find out whether it was possible but didn’t find much, so decided to knock up a quick test.
Here’s a file containing a couple of random variables (I called it test2.php):
<?php $var2 = "Something else"; $var = "Something";
And here’s a script that includes that file, outputs the variables from it, then opens the file, writes to it (replacing the variables) then includes the file and outputs the new variables (I called this test.php):
<p>Test writing to included file.</p>
<p>Including file: </p>
<?php include('test2.php'); ?>
<p>Writing vars:</p>
<?php echo '$var: ' . $var . '<br />$var2: ' . $var2; ?>
<p>Opening and writing to file:</p>
<?php $file = fopen('test2.php', 'w') or die('Couldn\'t open file.');
fwrite($file, '<?php
$var = "Abradacadabra!";' . "\n" . '$var2 = "Fooey!";');
fclose($file);
include('test2.php');
?>
<p>Echoing new vars: </p>
<?php echo '$var: ' . $var . '<br />$var2: ' . $var2;
And the output of all this is:
Test writing to included file. Including file: Writing vars: $var: Something $var2: Something else Opening and writing to file: Echoing new vars: $var: Poohead! $var2: Shitbum!
Perfect! My included file has been updated with the new info. Note that you do need to include it again otherwise PHP will not know those variables have been changed.
I’m off to write my upgrade script now…
0 Comments.