Simple PHP login code example



While tasked to code my very first php program, I did some googling.. who codes from scratch these days?.. but while googling, the sample codes were mind boggling.. me, the google-queen I am, will not fail.. after much soul code-searching, I found the forum posting here easiest to follow.. I copied the codes over to preserve the knowledge in case the forum can't be assessed any longer..

what gibberish mess right? ahh.. to be honest, I find joy writing codes.. as long as there is absolutely NO deadline.. ahh, what joy to see these gibberish turned into some webpages that can be responded to.. it's fun.. honest!



Step 1 - create a table dbUsers with the scripts below:

CREATE TABLE dbUsers(
  id int NOT NULL AUTO_INCREMENT,
  username varchar(16),
  password char(16),
  email varchar(25),
  PRIMARY KEY(id),
  UNIQUE (username)
)


Step 2 - create a file dbConfig.php with the codes below:
<?
  // 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);
?>


Step 3 - create a file register.php with the codes below:
<?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
       
?>



Step 4 - create a file login.php with the codes below:
<?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>";
 
}
       
?>



Step 5 - create a file members.php with the codes below:
<?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>";
?>



Step 6 - create a file logout.php with the codes below:
<?php
session_start
();
session_unset
();

session_destroy
();
// Logged out, return home.
Header("Location: index.php");
?>



(2011-08-11 22:48:35 SGT) [techie-geekie] Permalink


Comments:

Post a Comment:

Comments are closed for this entry.





Most popular blog postings in Biow's world:

  1. PSLE Aggregate Calculator and PSLE T-Score Calculator Online
  2. Interactive map for Secondary One Posting after PSLE
  3. 2013 PSLE cutoff points to 2014 Secondary 1
  4. 2012 PSLE cutoff points to 2013 Secondary 1
  5. 2011 PSLE cutoff points to 2012 Secondary 1
  6. 2014 O-Levels cut off point to JC (Junior College) in Singapore
  7. 2013 O-Levels cut off point to JC (Junior College) in Singapore
  8. 2012 O-Levels cut off point to JC (Junior College) in Singapore
  9. 2011 O-Levels cut off point to JC (Junior College) in Singapore
  10. 2010 O-Levels cut off point to JC (Junior College) in Singapore
  11. HDB toilet door replacement
  12. Recipe: Honey Vanilla Pound Cake Recipe by Ina Garten of Barefoot Contessa
  13. resignation letter for less than tender notice sample


Featured articles in Biow's world:

  1. Singapore Maths P1 Worksheet Online Generator - Problem Sums
  2. Singapore Maths P2 Worksheet
  3. Canon DSLR Tutorial Guide for Beginners
  4. Cake Decoration 101 - How to cream / frost a cake
  5. Cake Decoration 101 - Shell Piping
  6. Freezing Expressed Breastmilk (EBM) in 3 steps
  7. Another way to freeze Expressed Breastmilk (EBM)
  8. Storing of Expressed Breastmilk (EBM)
  9. How Breastfeeding Benefits Add Up
  10. Do not use glass bottle to freeze your precious breastmilk



Search

Sponsored Links

Categories

Tags

art_n_craft

birthdays

career

cny

cut-off

cut-off_jc

cut-off_psle

cut-off_uni

education

family

image_tools

k-drama

maths

movies

mr_clever

mr_earnest

mr_steady

ms_chatterbox

ms_excel

office2003

p1

p2

p3

school

science

singapore

syllabus

travel

tutorial

windows
Links


Navigation

Front Page
Weblog
TagsIndex
Privacy Policy
Login
Decals





rss feed for in Biow's World..

powered by Roller