Simple login script?

Like mentioned in one of my previous blogs, in order to start any tutorial in which requires a database you need to download MySQL and PHP which works simultaneously together. Once you have downloaded these two, and preferably Apache to view your final outcome, (which I can assure you is one of the hardest parts) you can start on one of these simple tutorials I found at : http://www.trap17.com/index.php/php-simple-login-tutorial_t7887.html Within this tutorial it gives you a step-by-step guide looking at creating a simple login section. 

  1. After getting MySQL and PHP up and running on your computer, you need to create 4 blank PHP web pages entitled: register.php, login.php, members.php, and logout.php.
  2. Once these have been created and up and running, we need to create a database in MySQL in order to store the users information. The code they used is

 Name the table “dbUsers.” It will need 4 fields:

[I]Name             Type                 Addition[/I]
id                  int(10)              Primary Key, AUTO_INCREMENT
username            varchar(16)          Unique
password            char(16)          
email               varchar(25)   

  1. When this is done we need to start creating and designing the registration page. This can be done by creating a PHP document called dbConfig.php. This file about to be created contains the coding to enable PHP and MySQL to communicate with one another. With the code above you need to enter users into the equation by adding them into the MySQL saved file.
  2. Then into the dbConfig.php file add the following code to call MySQL for the database information

 <?
// Replace the variable values below
// with your specific database information.
$host = “localhost”;
$user = “UserName”;
$pass = “Password”;
$db   = “dbName”;

// This part sets up the connection to the
// database (so you don’t need to reopen the connection
// again on the same page).
$ms = mysql_pconnect($host, $user, $pass);
if ( !$ms )
{
echo “Error connecting to database.\n”;
}

// Then you need to make sure the database you want
// is selected.
mysql_select_db($db);
?>   

  1. You need to then set up the registration page we created in step 1. (Register.php) in order to do this inset this code into the document

 <?php

// dbConfig.php is a file that contains your
// database connection information. This
// tutorial assumes a connection is made from
// this existing file.
include (“dbConfig.php”);

//Input vaildation and the dbase code
if ( $_GET[“op”] == “reg” )
 {
 $bInputFlag = false;
 foreach ( $_POST as $field )
  {
  if ($field == “”)
   {
   $bInputFlag = false;
   }
  else
   {
   $bInputFlag = true;
   }
  }
 // If we had problems with the input, exit with error
 if ($bInputFlag == false)
  {
  die( “Problem with your registration info. ”
   .”Please go back and try again.”);
  }

 // Fields are clear, add user to database
 //  Setup query
 $q = “INSERT INTO `dbUsers` (`username`,`password`,`email`) ”
  .”VALUES (‘”.$_POST[“username”].”‘, ”
  .”PASSWORD(‘”.$_POST[“password”].”‘), ”
  .”‘”.$_POST[“email”].”‘)”;
 //  Run query
 $r = mysql_query($q);
 
 // Make sure query inserted user successfully
 if ( !mysql_insert_id() )
  {
  die(“Error: User not added to database.”);
  }
 else
  {
  // Redirect to thank you page.
  Header(“Location: register.php?op=thanks”);
  }
 } // end if

//The thank you page
elseif ( $_GET[“op”] == “thanks” )
 {
 echo “<h2>Thanks for registering!</h2>”;
 }
 
//The web form for input ability
else
 {
 echo “<form action=\”?op=reg\” method=\”POST\”>\n”;
 echo “Username: <input name=\”username\” MAXLENGTH=\”16\”><br />\n”;
 echo “Password: <input type=\”password\” name=\”password\” MAXLENGTH=\”16\”><br />\n”;
 echo “Email Address: <input name=\”email\” MAXLENGTH=\”25\”><br />\n”;
 echo “<input type=\”submit\”>\n”;
 echo “</form>\n”;
 }
// EOF
?>   6.      We need to next check that the information provided by the registered user corresponds with the information within the set up database. Since when the user registered, we encrypted their password using the MySQL PASSWORD() function, we re-encrypt the password the user supplied in the login form and cross-check this with the existing value in the dBase. If login information is O.K., then we need to use sessions to store the user’s ID so they can access member-only content. <?php
session_start();
// dBase file
include “dbConfig.php”;

if ($_GET[“op”] == “login”)
 {
 if (!$_POST[“username”] || !$_POST[“password”])
  {
  die(“You need to provide a username and password.”);
  }
 
 // Create query
 $q = “SELECT * FROM `dbUsers` ”
  .”WHERE `username`='”.$_POST[“username”].”‘ ”
  .”AND `password`=PASSWORD(‘”.$_POST[“password”].”‘) ”
  .”LIMIT 1″;
 // Run query
 $r = mysql_query($q);

 if ( $obj = @mysql_fetch_object($r) )
  {
  // Login good, create session variables
  $_SESSION[“valid_id”] = $obj->id;
  $_SESSION[“valid_user”] = $_POST[“username”];
  $_SESSION[“valid_time”] = time();

  // Redirect to member page
  Header(“Location: members.php”);
  }
 else
  {
  // Login not successful
  die(“Sorry, could not log you in. Wrong login information.”);
  }
 }
else
 {
//If all went right the Web form appears and users can log in
 echo “<form action=\”?op=login\” method=\”POST\”>”;
 echo “Username: <input name=\”username\” size=\”15\”><br />”;
 echo “Password: <input type=\”password\” name=\”password\” size=\”8\”><br />”;
 echo “<input type=\”submit\” value=\”Login\”>”;
 echo “</form>”;
 }
?>

7 Next is to set up a members area

members.php

Now that the user has logged in successfully, and has his id, username, and login stored in session variables, we can start working with member-only content. A major thing to remember is that any page you want to carry session data over to you must declare a session_start(); at the top of your code.

CODE<?php
session_start();

if (!$_SESSION[“valid_user”])
{
// User not logged in, redirect to login page
Header(“Location: login.php”);
}

// Member only content
// …
// …
// …

// Display Member information
echo “<p>User ID: ” . $_SESSION[“valid_id”];
echo “<p>Username: ” . $_SESSION[“valid_user”];
echo “<p>Logged in: ” . date(“m/d/Y”, $_SESSION[“valid_time”]);

// Display logout link
echo “<p><a href=\”logout.php\”>Click here to logout!</a></p>”;
?>  7.      And lastly when the user exits the website we should be able to offer the ability for the user to destroy the session variables. In order to do this open up the logout.php document and copy and paste this coding  <?php
session_start();
session_unset();

session_destroy();
// Logged out, return home.
Header(“Location: index.php”);
?>  This tutorial is pretty straight forward, and the coding seems reasonable enough to read and understand. However the coding is very long winded therefore you can see how many files and how long the coding for each section needs to be. For login sections alone it requires 4 pages, what about all the other sections people require? How many files will you need to create? Marc  Http://marc.izonedesign.co.uk

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: