Developing Custom PHP Sessions - Using Our Sessions
(Page 4 of 5 )
Let's start by creating a new file named login.php. Add the following code to login.php:
<?php
include "sess.php";
if($login) {
$sess = new session;
$sess->start();
$sess->register($username);
header("Location: welcome.php");
}
?>
<html>
<head>
<title>login</title>
</head>
<body>
<form method="post" action="<?= $PHP_SELF; ?>">
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<br>
<input type="submit" name="login" value="Login">
</body>
</html> The code above has our login form and if it's submitted it will initialize the class and use the proper functions to start and register the values. Then the user is redirected to the welcome.php page.
Last, but surly not least, we need to create our welcome.php page:
<?php
include "sess.php";
$sess = new session;
if($logout == "yes") {
$sess->destroy();
header(“Location: login.php”);
exit;
}
$sess->read();
?>
<html>
<head>
<title>welcome</title>
</head>
<body>
Welcome, <?= $sess_val; ?><br>
<a href="<?= $PHP_SELF; ?>?logout=yes">Logout</a>
</body>
</html> Since this page is the first one to use our sessions with the passing key, we call the read() function to fetch the value. As seen in the read() function, we saved the value to $sess_val so where we want that data to appear we print it to the user. Then we offer a link to log out, which uses the destroy() function to kill the current session.
Next: Conclusion >>
More MySQL Articles
More By Brian Rosner