faqts : Computers : Programming : Languages : PHP : Common Problems

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

20 of 21 people (95%) answered Yes
Recently 7 of 7 people (100%) answered Yes

Entry

Is there any way to maintain a global variable which will be accessible from all scripts?

Dec 26th, 2005 03:48
Praveen Kumar Kukkapalli, Rob Garth, Ben Munoz, Matt Gregory, Vshal Seth,


You can assign your value to $_GLOBAL array so that that value will be
available with in the application.

$GLOBALS['x'] = "Hi";

Then you can access the value of 'x' with in your application.


There are only 3 ways of doing this.

Create an environment variable for your scripts.
Save the value to a file, (like an INI file)
Save the value to a database.

PHP does not store any variables between scripts because each script 
has a unique run id and memory is released after execution.

-----------------------------------------------------

If you need to pass variables from one script to another you can
append it to the URL:
<a href="script.phtml?variable=value">link</a>

Or you can use a hidden input in a form:
<form action="script.phtml">
<input type=hidden name=variable value=value>
<input type=submit>
</form>

Note: you can't do this: <form action="script.phtml?variable=value">

The downside: it can get hairy with many variables.

If you have PHP4, you definitely want to look into session functions.

-----------------------------------------------------

If PHP is running on a unix host - you should be able to easily set a
shell variable and make a system call to grab when you need it.