PHP Login Page

Associate
Joined
2 Sep 2007
Posts
2,001
Hi All, I'm back. :D

I want to create a very simple login process. There will only be one user so I won't need to authenticate with a database. I know I need to create a simple form with two textboxes and a button.

How do I setup the session variables in my validatelogin.php?

I've found this code on this forum which I can use in my pages which I need to secure: -

Code:
if($_SESSION['username'] === "username" && $_SESSION['password'] === "password") {
        session_regenerate_id();
	$logged_in = 1;	
} else {
        $_SESSION = array();
        session_destroy();
        header("Location: index.php");
}
 
Ok I've created a simple login page.

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Login Page - Moodle Ban List Functions</title>
</head>
<body>
   
    <h2>
        <strong>Moodle Ban List Functions - Login Page</strong></h2>
    <form id="frmLogin" name="frmLogin" method="post" action="loginbanlist.php">
    <p>
        Username:
        <input id="txtUsername" type="text" /></p>
    <p>
        Password:
        <input id="txtPassword" type="text" /></p>
    <input id="LoginButton" type="submit" value="Login" />
    </form>
</body>
</html>

Here is my loginbanlist.php

Code:
<?php
	session_start(); 
	$_SESSION['username'] = '$_POST[txtUsername]'; 
	$_SESSION['password'] = '$_POST[txtPassword]'; 
      header("Location: moodlebanlist.php");
?>

The moodlebanlist.php has the code from the first post at the beginning. Although when I login using 'username' and 'password' it still throws me back to index.php. Any ideas?
 
I've spotted an error

$_SESSION['username'] = '$_POST[txtUsername]';
$_SESSION['password'] = '$_POST[txtPassword]';

remove the quotes around the $_POST[txtUsername], etc. Still not working through. :(
 
Try putting the quotes in the txtUsername and txtPassword bit instead:

$_SESSION['username'] = $_POST['txtUsername'];
$_SESSION['password'] = $_POST['txtPassword'];
 
If you're simply trying to secure a website and don't need a "logged in as: xxx" style message on your page you might be better off just using simple http authentication via a .htacess file.

If you do want to show some kind of logged in notice, then here's the way I would approach it in pseudo-code:

Code:
If no username / authenticated flag in the session
   was the login form was submitted?
      do the submitted values match username / password?
         store the username / authenticated flag in the session
         user is now logged in
      if not
         inform the user their login info was bogus
         re-display the login form
   if not
      display the login form
else 
   user is already logged in
 
Back
Top Bottom