phrants.net
2Fév/100

PHP – Global Variables / Passing Variables to another page

I was at a total loss when trying to set a variable that I could use from one PHP page to another. The POST and GET functions worked to a point for the basic stuff, but I was quickly outgrowing the introductory course. I wanted to do something like an #include for each page, or to set a global variable that each individual page could access. It was extremely difficult to realize, but I finally figured out that what I wanted to do was to set a Session variable. As long as the session variable is set, you can use it at any time from any of your other PHP pages. This turned out to be incredibly easy:

session_start(); //this goes at the top of each page - it either creates or maintains a session with the server

$_SESSION['user_name']; //creates a session variable and can be assigned to a regular variable

$user_name = $_SESSION['user_name']; //now the 'local' variable is assigned from the 'global'

Session variables are amazing, you can just call on them from out of the blue and they will be there as long as the session is open. Sessions do expire after a prolonged period of time or if you close the browser or call on a PHP function to destroy it.  I had a great "Aha!" moment once I realized that I could assign a variable in one file and easily use it in any other PHP file. I guess this is what happens when you teach yourself PHP from online tutorials.

Commentaires (0) Trackbacks (0)

Aucun commentaire pour l'instant


Laisser un commentaire


Aucun trackbacks pour l'instant