November 08 2012

Access PHP variable from anywhere

Sometimes you need to transport the value of a variable from one page to another. In order to save using the SQL, you can simply write it out in a file, and fetch from it again. This is a simple strategy that came in handy on a recent project (more details soon).

So, here is the code:

[sourcecode language="html"]
< ?php
include 'vars_in_file.php';
//The "include" prints at its location is written in the file vars_in_file.php
$my_var++;
//Do something to your variable
$var_str = var_export($my_var, true);
//The command var_export outputs or returns a parsable string representation of a variable
$var = "";
//Here we write what we want to be the content of the file vars_in_file.php
file_put_contents('vars_in_file.php', $var);
//Finally write to file. Ready to be called again at a later time.
? >
[/sourcecode]