After my last article about Session Management in PHP4, I got several
emails from people that had problems implementing what I tried to
describe. All theese emails had the same question:
Can you give me example code ? Yes, sure I can.
I will assume that you have read my previous article
(
it's here in case you missed it). As I described earlier, you
have to tell PHP that the current page use session variables by
calling the
session_start() function. Once this function
is called, you are free to register any variable that you have bound as
a session variable. This is done using the
session_register()
function.
The first example (page1.php):
<?php
session_start();
$my_session_variable = "some value";
session_register("my_session_variable");
?>
What this does is that it registers the variable
my_session_variable as a session variable. This means that
the variable will be alive (keep it's value) across page-accesses, as
long as you call the session_start() function on all pages
that need access to the my_session_variable variable.
Example 2 (page2.php):
<?php
session_start();
print "Value of 'my_session_variable': $my_session_variable";
?>
Try this out, you'll see that the variable kept it's value across pages!
Using session variables for authentication in conjunction with a database
is just as simple. Create a login-page gives the user a userid and
password form and posts to another PHP page (this example uses mysql):
<?php
session_start();
if (@$userid && @$password) {
$res = @mysql_query("SELECT userid FROM users WHERE userid='$userid' AND password='$password'");
if(@mysql_num_rows($res) != 0) {
$verified_user = $userid;
session_register("verified_user");
}
}
Header("Location: your_main_page.php");
?>
Now, on 'your_main_page.php', you call session_start() and
then you can check the verified_user variable to see if the
user has been authenticated (and who he is). As simple as that.
There's alot more uses for session variables though, I use it for letting
the load of my database by caching certain values in the session rather
than reading them from the database on each page access.
Another small addition to my previous article: You can store
objects in session variables as of Beta 3 of PHP4. Several people pointed
this out to me, so I thought I'd tell you all.