This is all fairly straight forward. Before ANY output is sent to the browser (including whitespace outside of the <?php and ?> tags), you must call session_start.
Here's a simple example:
-- login.php --
Code:
<?php
session_start();
// attempting to log in after already logged in?
if(isset($_SESSION['logged_in']) && (true === $_SESSION['logged_in']))
{
header('Location: index2.php');
}
// did user submit the login form?
if(isset($_POST['username']))
{
if(($_POST['username'] == 'nikolai') && // you have to figure out
($_POST['password'] == 'password')) // how to verify logins
{
// valid login, add username to session.
$_SESSION['logged_in'] = true;
$_SESSION['username'] = $_POST['username'];
// redirect to index2.php
header('Location: index2.php');
}
else
{
echo "<b>Invalid login, please try again.</b>";
}
}
echo "<form method=\"post\" action=\"{$_SERVER['PHP_SELF']}\">\n"
. " Username: <input type=\"text\" name=\"username\"><br />\n"
. " Password: <input type=\"password\" name=\"password\"><br />\n"
. " <input type=\"submit\" name=\"submit\" value=\"Login\">\n"
. "</form>\n";
?>
--index2.php --
Code:
<?php
session_start();
// verify logged in, if not, redirect to login page.
if(! isset($_SESSION['logged_in']))
{
header('Location: login.php');
}
// if user is logging out, destroy session and redirect to login page.
if (isset($_POST['logout']))
{
unset($_SESSION); // delete session variable
session_destroy(); // destroy data written to server filesystem
header('Location: login.php');
}
// If we got here, session exists and user is NOT logging out.
// Count how many times the user has visited this page.
++$_SESSION['count']
echo "Welcome, {$_SESSION['username']}!<br />\n";
echo "You've visited this page {$_SESSION['count']} times this session.<br />\n";
// logout button:
echo "<form method=\"post\" action=\"{$_SERVER['PHP_SELF']}\">\n"
. " <input type=\"submit\" name=\"logout\" value=\"Logout\">\n"
. "</form>\n";
?>
As always, it's a good idea to read through the manual. There's LOTS of documentation and sample code available.
http://www.php.net/session
Take care,
Nik
http://www.bigaction.org/