views:

421

answers:

7

Does PHP have global variables that can be modified by one running script and read by another?

A: 

Not as such, but you can use cookies or sessions to maintain data for duration of a user's browsing experience, or you can write to a database or file on-disk if the information needs to persist beyond that.

bcat
+1  A: 

The only one which could be accessed between scripts is the superglobal $_SESSION array. This is because whatever you store in the array is sent to a cookie, which can then be picked up by the next PHP script.

Global variables simply mean that they can be accessed in the script regardless of the scope; that doesn't mean they can be sent between scripts.

So either you have to transfer the variables using the $_SESSION array (this stores a cookie on the client computer, so don't sent any sensitive information through that array) or you can either POST or GET between the scripts to send the variables.

BraedenP
The session data itself is not stored in a cookie but on the server. Only the session id is sent to the client as a cookie header.
VolkerK
+1  A: 

Each request is handled by a php instance of its own. Global variables in php are only accessible from within the same php instance. However you can use something like the memchached module to share data between different instances (which should usually be faster than writing the data to the filesystem).

VolkerK
+6  A: 

No, by design PHP is a "share nothing" architecture, which means nothing is shared between processes running at the same time or between requests running one after another. There are ways to share data, but you have to do it explicitly.

If you just want to share between 2 requests from the same user, sessions or cookies might be the way to go.

If you want to share between multiple users, you probably want some sort of shared persistence, either short term in a cache (eg. memcached) or more robust like a database.

Either way, the data is actually being retrieved and reconstructed on each request. It's just handled automatically for you in the case of sessions.

Brenton Alker
+1  A: 

You can actually do this using shared memory, or APC (which is using shared memory itself).

Frank Farmer
A: 

Another common substitution for global variables in PHP is the shared use of a database like MySQL (albeit not a perfect one)

HipHop-opatamus
A: 

Global variables are bad in most programming. They're especially bad in multithreaded/multiuser systems like webapps. Avoid. If you must use global variables (rather than global constants) put them in a database with transactions guarding updates.

Since you talk about different scripts though, it sounds like what you really want is a web application framework in a more application oriented language --- something like Django (python) or Rails (ruby). These let you think of your code much more like a cohesive PROGRAM, rather than a lot of loosely connected scripts that process web requests.

Lee B