As I journey though my life as a professional web developer (and software developer), I encounter more and more of user login and session maintenance topics. It applies to all webpages these days be it in any platform; ASP.NET, JSP, PHP, PERL. There are tonnes of example, description, explanations and lecture notes out there, but the purpose of this note is not to get very academic but to give all you programmers a quick way to get start with a working example. So for the benefit of all new and experienced programmers alike, here are the steps in creating a login session based explanation and example codes.
Enjoy!
The Demo
Here is the link to the demo.
And here is are the codes in zip file.
The Codes
login.php : The “login.php” file the login screen
<?php // Begins the session, you need to say this at the top of a page or // before you call session code // Note that, you will need this statement all the time session_start(); // Checking whether the session is already there or not if true // then header redirect it to the home page directly if(isset($_SESSION['use'])) { header("Location:home.php"); } if(isset($_POST['login'])) // Checks if user clicked login button { // Get value from encoded URL (POST) $user = $_POST['user']; $pass = $_POST['pass']; // Check for valid username and password (valid username // and password for this example is claire and iknoweverythng) if($user == "claire" && $pass == "iknoweverything") { // Store username in session variable $_SESSION['use']=$user; // On successful login redirects to home.php echo '<script type="text/javascript">'; echo ' window.open("home.php","_self");'; echo '</script>'; } else { echo "Invalid username and/or password"; } } ?> <html> <head> <title>Login Page</title> </head> <body> <form action="" method="post"> <table width="200" border="0"> <tr> <td>UserName</td> <td> <input type="text" name="user"> </td> </tr> <tr> <td>Password</td> <td> <input type="password" name="pass"> </td> </tr> <tr> <td colspan="2"> <input type="submit" name="login" value="login"> </td> </tr> </table> </form> </body> </html>
home.php : The “home.php” file is for homepage (the main landing page).
<?php // Begins the session, you need to say this at the top of a page or // before you call session code // Note that, you will need this statement all the time session_start(); ?> <html> <head> <title>Home</title> </head> <body> <?php // If session is not set then redirect to login Page if(!isset($_SESSION['use'])) { header("Location:Login.php"); } echo $_SESSION['use']; echo "<br>"; echo "Login Successful"; echo "<a href='logout.php'> Logout</a> "; ?> </body> </html>
logout.php : The “logout.php” file logs your user out of the session.
<?php session_start(); echo "Logout Successfully"; session_destroy(); // Destroys the session header("Location: login.php"); ?>