Jump to content



Welcome to KnowledgeSutra - Dear Guest , Please Register here to get Your own website. - Ask a Question / Express Opinion / Reply w/o Sign-Up!
- - - - -

Php Simple Login Tutorial


102 replies to this topic

#1 HmmZ

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 362 posts
  • Location:The Netherlands

Posted 03 March 2005 - 08:56 AM

I have been quite busy lately, trying to design and code my site (far from done XD). And after having learned how to make a simple login, I will try to write my own tutorial, for you :D

the tutorial

Step 1:
The first step in designing a member system is to plan out exactly what you need. A common impulse among programmers is to jump right in and start coding. I'll be honest and admit that I'm guilty of this more so than anyone. However, since I'm in control of this conversation (yes!), you'll have it all planned out by reading through this before you even see any code.

What will you need to start?
First of all, you need a server that supports a CGI or Server-side language. For this tutorial, it's PHP. I won't be directing any attention to any other language at this time, so although the concepts will be similar, the code will be entirely different than something you might use in Perl or ASP. As a side note, it is possible to perform a member system simply using JavaScript, but it would not be remotely secure because JavaScript is client-side (thus able to be viewed by anyone), and even if you had a one-way encryption script it would not be feasible because of the pain of hard-coding usernames and encrypted passwords into the HTML document.

Second, at least for our purposes, you need a database. Preferably MySQL. PHP and MySQL go hand-in-hand, so a lot of servers tend to match the two up. Thus, since we're talking PHP, we may as well talk MySQL.

Third, you will need 4 blank PHP web pages entitled: register.php, login.php, members.php, and logout.php. After you have these pages created and open, we're ready to start.

Step 2: Database

If we want to design a members system, we'll need a database. So all we need to do in this step is to create the table we will use to manage the user's login information. Note that the schema we use here is quite simple, and is only simplified to help you see how it works.

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)

Once you've made the database table, you're ready to design and code the registration page.

Create a File to Connect to your Database

Create a new file and name it dbConfig.php. This file will contain the PHP code that will connect to the MySQL database, and select the correct database. Make sure you have added users to your MySQL database with read/write or admin access, then place this type of code into the dbConfig.php file:

<?
// 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: Register

register.php

On your registration page, you need to create a web form that will allow the user to plugin a username, password, and their e-mail address. Then, also on your page, add code that runs only when information has been passed via the form. Finally, display a "Registration Successful!" message to the user.

<?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: Login

login.php

Now in PHP, first we need to check the username and password against the information stored in the 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>";
  }
	?>

Step 5: 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.

<?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: Logout

logout.php

Ah, although it would be nice if our user's never left our web sites, we should give them to opportunity to log out and destroy the session variables if they so choose. It's quite easy to do, and you can just copy and paste this one.

<?php
session_start();
session_unset();

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

That's about it!. I used many simple examples hoping that you will learn how the internal systems work so you can expand on them and design a system that's just right for your needs. Have fun! :D

#2 Dragonfly

    Privileged Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 702 posts

Posted 03 March 2005 - 04:40 PM

Thanks, I have both php and MySQL installed in my laptop. I think that steps you've mentioned here are easy to follow and easy to understand. I'm beginner in PHP and have been following closely any topic related to php.

Hope I can implement the above code and make use of it in the future. I should start testing it in my local computer. Thanks.

#3 HmmZ

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 362 posts
  • Location:The Netherlands

Posted 03 March 2005 - 08:57 PM

Thanks for the positive feedback, I haven't implemented, nor tested the code myself (just checked to see if it actually showed up), so if any problems persist, tell me about it, so I can adjust the code hoping it could fix it, if there is a flaw and you know the solution, replying with both the flaw and the solution is always welcome of course :D

#4 bjrn

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 378 posts

Posted 03 March 2005 - 10:33 PM

If someone is planning on implementing something like this here on their Trap17 account, I suggest you use Pear. When you have people logging into things on your site, you want to make sure that there is no possibility of sql injection. Pear's DB prepared statement function prevents SQL injection attacks. It's very handy.

Something like this could work
require_once("PEAR.php");
require_once("DB.php");
PEAR::setErrorHandling(PEAR_ERROR_DIE, "Aaaaargh! Error: %s");
$conn = DB::connect("mysql://dbuser:dbpassword@localhost/dbname");
$preparedstatement = $conn->prepare('INSERT INTO dbUsers (username, password, email) VALUES (?, ?, ?)');
$data = array($_POST['username'], $_POST['password'], $_POST['email']);
$conn->execute($preparedstatement, $data);
Please note that I haven't tested this code, it should work, but there might be some stupid typo somewhere. :D

#5 karlo

    Privileged Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 632 posts
  • Gender:Male
  • Location:Philippines

Posted 04 March 2005 - 04:44 AM

bjrn, on Mar 4 2005, 06:33 AM, said:

If someone is planning on implementing something like this here on their Trap17 account, I suggest you use Pear. When you have people logging into things on your site, you want to make sure that there is no possibility of sql injection. Pear's DB prepared statement function prevents SQL injection attacks. It's very handy.

Something like this could work
require_once("PEAR.php");
require_once("DB.php");
PEAR::setErrorHandling(PEAR_ERROR_DIE, "Aaaaargh! Error: %s");
$conn = DB::connect("mysql://dbuser:dbpassword@localhost/dbname");
$preparedstatement = $conn->prepare('INSERT INTO dbUsers (username, password, email) VALUES (?, ?, ?)');
$data = array($_POST['username'], $_POST['password'], $_POST['email']);
$conn->execute($preparedstatement, $data);
Please note that I haven't tested this code, it should work, but there might be some stupid typo somewhere. :D

View Post

What are those? $conn->execute? How can I use "Classes"? how can I create my own? Where to use them? what's pear? do you know a tutorial for the classes/objects and pear? I thought to fetch the results, you must use a loop function. why did you only use "if" function?

#6 mahesh2k

    Trap Double Mocha Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 2,347 posts
  • Gender:Male
  • Location:Valley of Darkness
  • myCENT:67.95
  • Spam Patrol

Posted 04 March 2005 - 06:46 AM

That was an exceelnt login tutorial from you,i m looking for some of tutorials like this.anyway can you explain me
code below
echo "<p>User ID: " . $_SESSION["valid_id"];
echo "<p>Username: " . $_SESSION["valid_user"];
echo "<p>Logged in: " . date("m/d/Y", $_SESSION["valid_time"]);
code end

pls explain

#7 HmmZ

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 362 posts
  • Location:The Netherlands

Posted 04 March 2005 - 09:01 AM

Ouch, a double post :D

as for the code, the login script uses sessions, to store user id's and info to be able to show some stats of the user next time he logs on.

Besides that it looks nice, it also has a security feature, when a user sees the last logged in time, he can see if someone else has been on his account.

Hope that helped you explain?:D

#8 bjrn

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 378 posts

Posted 04 March 2005 - 05:03 PM

I'll try to explain the code

This imports the PEAR things to your script, PEAR.php and DB.php are standard scripts, available to everyone. Not something you have to upload or make yourself.
require_once("PEAR.php");
require_once("DB.php");

This makes sure you get a nice error message in case things go wrong
PEAR::setErrorHandling(PEAR_ERROR_DIE, "Aaaaargh! Error: %s");

This makes an connection object. You have to substitute 'dbuser' for your db username, same for dbpassword and dbname. I just put them there to show what goes where. Oh, and if you are connecting to a DB on another server you of course have to replace 'localhost' with the server ip.
$conn = DB::connect("mysql://dbuser:dbpassword@localhost/dbname");

Now you can use your connection object. This piece calls the prepare() function in the connection object and stores the resulting statement.
$preparedstatement = $conn->prepare('INSERT INTO dbUsers (username, password, email) VALUES (?, ?, ?)');

This is an array with values, the values will replace the '?'s in the preparedstatament.
$data = array($_POST['username'], $_POST['password'], $_POST['email']);

And finally you call the execute() function the the connection object has with the prepared statement and the array of values as parameters.
$conn->execute($preparedstatement, $data);


I don't really know much about PEAR. What I know I've learned from the official PEAR site and from Googling for specific bits.

#9 HmmZ

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 362 posts
  • Location:The Netherlands

Posted 04 March 2005 - 08:37 PM

Why is PEAR needed with this script, i don't think ive ever even heard of PEAR :D

The thing is, the script should most likely work without the PEAR thing won't it? If so, why make it more more difficult, it's supposed to be a "simple" login system, I'm currently working on my own complete membersystem, with pms and such, but I will probably keep it to myself, something has to be unique about my future community :D

#10 NotoriousZach

    Member [Level 1]

  • Kontributors
  • PipPipPipPip
  • 55 posts

Posted 20 March 2005 - 04:44 AM

Hey thanks for the great tutorial....I made mine where only people I have verified can see it......To do that I just added a feild in the database

On the new feild
Name = verified 
default=0

In login.php add this

."AND `verified`=1 "

In between

."AND `password`=PASSWORD('".$_POST["password"]."') "

AND

."LIMIT 1";

Hope you guys enjoy....And thanks again for the great script.

#11 hhPHP

    Newbie

  • Kontributors
  • Pip
  • 1 posts

Posted 20 March 2005 - 04:51 AM

Wow, good guide, this is some good stuff, keep up the goodness, you get a reputation point...

#12 snlildude87

    Moderator

  • Kontributors
  • PipPipPipPipPipPipPipPipPipPipPipPipPipPipPip
  • 2,325 posts
  • Location:Mawson, Antarctica

Posted 20 March 2005 - 05:15 AM

Welcome to trap17, hhPHP.

#13 elevenmil

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 470 posts

Posted 30 March 2005 - 01:07 AM

As many of you just might know, I'm tryin to get this log in and register stuff down, but I keep running into problems... For your tutorial I keep getting this message everytime I open my .php files in my browser.


Fatal error: Call to undefined function: mildawg_dbconfig() in /home/mildawg/public_html/dbConfig.php on line 20

any thoughts? Thanks for the help.

#14 HmmZ

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 362 posts
  • Location:The Netherlands

Posted 30 March 2005 - 05:16 AM

Hmm,

the error says theres a problem on line 20...
// Then you need to make sure the database you want
// is selected.
mysql_select_db($db);
?>

try the following:
mysql_select_db("$db",$ms);

if that doesnt work you can try to take off the apostrophes, if the problem still persists please reply again

P.S. please don't forget that Trap17 uses your cPanel username in db usernames and dbs, e.g. cpanelusername_dbusername and yourcpanelusername_dbname.

#15 cragllo

    Privileged Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 933 posts

Posted 31 March 2005 - 08:34 AM

I have not tried this YET, but i read through the code, in register.php

where is the information inserted into the db?
  // Create query
 $q = "SELECT * FROM `dbUsers` "
  ."WHERE `username`='".$_POST["username"]."' "
  ."AND `password`=PASSWORD('".$_POST["password"]."') "
  ."LIMIT 1";
I see taht bit, but that just selects data out of the db dosent it?
Correct me if im wrong, just learning... :)

#16 elevenmil

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 470 posts

Posted 31 March 2005 - 08:55 AM

Hmmz, I adjusted my code and the error went away, but when I went to try it out and register, yep, I hit another roadblock...it says...

Error: User not added to database.


...frustrating...

what do you make of this?

#17 elevenmil

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 470 posts

Posted 31 March 2005 - 09:14 AM

Sorry about the double post...but its 4 AM and I'm goin to bed but I saw somethin else...in addition to my previous post whenever I registered to check what would happen and it said user not added to database...I went to my phpMyAdmin and looked at my table....and my username WAS added...this just adds to my confusion

Any help?

#18 HmmZ

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 362 posts
  • Location:The Netherlands

Posted 31 March 2005 - 01:19 PM

I think I see the problem, its checking a wrong query, try the following (old code first to see where you can find it)

// 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.");
  }

replace if(!mysql_insert_id()) with this:
if(!$r)

let me know if that fixes your problem

#19 elevenmil

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 470 posts

Posted 31 March 2005 - 06:43 PM

I inserted your code, but nothing changed, still got the error user not added to database thingy....

What else can you suggest? Thanks...I'll keep messin around with it

#20 rambo406

    Newbie [Level 1]

  • Kontributors
  • Pip
  • 13 posts

Posted 02 April 2005 - 08:25 AM

i am noob in PHP so i just follow the instruction thanks man

#21 elevenmil

    Super Member

  • Kontributors
  • PipPipPipPipPipPipPipPipPip
  • 470 posts

Posted 03 April 2005 - 08:22 AM

Hey guys I found a tutorial that fixed my problem...thanks to all that tried to help...I believe the tutorial link I found is under the hosted members area, it is a really easy step by step guide that include improvements to the original php codes, thanks again everyone.

#22 nickmealey

    Premium Member

  • Kontributors
  • PipPipPipPipPipPipPipPip
  • 156 posts
  • Location:Washington, USA
  • Interests:I like sports, baseball mostly. I like food and computers. And i'm not ashamed to be a Christian.

Posted 06 April 2005 - 07:08 PM

I like that alot! I'm trying to lurn php and mySql, and that help. Two thumbs up!

#23 Garath

    Newbie

  • Kontributors
  • Pip
  • 1 posts

Posted 06 March 2007 - 01:24 AM

Whenever I try this, it always says "ERROR:Not added to the database."

<?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
?>


#24 Mr-Slowly

    Newbie

  • Validating
  • Pip
  • 1 posts

Posted 21 March 2007 - 05:29 PM

nice tut man thanx :lol:

#25 MCSESubnet

    Newbie

  • Kontributors
  • Pip
  • 5 posts

Posted 21 March 2007 - 07:50 PM

Here is the MD5 alternative:


<?PHP 
$user_name = $_POST['u_name']; 
$password = $_POST['pass']; 

//db connection string 
$db = mysql_connect("localhost","root","pass"); 
mysql_select_db("my_database",$db); 
//replace the above values with your actual database val 

//We will now retrive the password from the database 
$sql_query = mysql_query("SELECT password FROM user_data WHERE user_name='$user_name'",$db); 
$rs = mysql_fetch_row($sql_query); 

//comparing passwords 
Note before we can compare the password we use md5() to encrypt the $password becuase the password that we retrive from the database is in the encrypted form. 
if(md5($password) != $rs[0]) 
echo "ERROR: Invalid User"; 
else 
echo "Congrats, Password is correct!"; 
?>


( I pulled this off www.phpbuddy.com ) Although this shows you how fast and easy it is to use MD5 and personally I prefer it over PEAR




Reply to this topic


This post will need approval from a moderator before this post is shown.

  


1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users