Friday, March 30, 2007

Using SESSION in PHP

Passing variable(s). Here is simple example of how to pass variable(s) between PHP files.

page1.php <?php // This will start or resume session. session ID // will be transfer between via GET, POST, or cookie. session_start(); $_SESSION['valid_user'] = 'me'; ?>
page2.php <?php session_start(); echo $_SESSION['valid_user']; ?>
If you want to end the session, you first delete the session variable(s),
session_start(); // you always need to call this first unset($_SESSION['valid_user'];
Delete cookie if you're using cookie to transfer session ID
if (isset($_COOKIE[session_name()])) { setcookie(session_name(), '', time()-42000, '/'); }
And call,
session_destroy();
Note: session_start() called before sending the header. Which means no HTML or PHP output before calling the function first.

No comments: