Sunday, September 05th, 2010 Welcome Guest! - Register    
Sign In
Forget your password?
Username:  
Password:   
Stay Logged in for:

Donations to date: $62.50
Support This Site Today!

Top 3 Active Posters
Ntsmarkv
SetoTK
mcstec

Latest Forum Posts
dbconfig video guide...

kasl products on sale!...

forum topic...

webhost 2.0...

download page demo's d...

edit post in forum...

portal & users...

webhost 2 language sys...

cosmetic bug : no aft...

forum subtopics...


Forums
Forums
On Sale!
Downloads
Bookmarks
Bookmarks
Contact Us
Contact Us

Sale is Over

The sale in the download's section is now over.


Posted by ~Ntsmarkv on Monday, August 31st, 2010 10:03 PM MST

PHP - Login/Logout Script


When building a dynamic website, one of the best and most common thing that a webmaster does is store the information of users in a database.  But how does the website know who is who?  That is where the login page comes in.  Here is how a login script works:

1.  The user enters their username and password and submits the form
2.  The server compares the information that the user entered against the database.
3.  If the info matches a row in the database, the row will be returned.  If it doesn't match, the number of rows is 0 and nothing is returned.
4.  Assuming that the info matched what was in the database, the website sets a cookie.  A cookie is a file that stores the user data for the amount of time that the website specifies (the webmaster sets the parameters for the time).
5.  While the cookie is set, the information about the user can be retrieved from the cookie.

This article will show you how to match a user's info against the info in the MySql database.  I will give you instructions that you can try as you read this article.

To start out, you first need a table in the database.  I will call the table "users" - if you already have a users table in your database, you may call it something else - but keep in mind I will reference the users table only.  Here is the sql code to generate the users table.

--------------------------------

CREATE TABLE `users` (
  `user_id` int(10) NOT NULL auto_increment,
  `username` varchar(30) NOT NULL default '',
  `password` varchar(32) NOT NULL default '',
  `email` varchar(50) NOT NULL default '',
  PRIMARY KEY  (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
INSERT INTO `users` VALUES (1, "john", "johnspassword", "john@void.null");
INSERT INTO `users` VALUES (2, "bob", "bobspassword", "bob@void.null");
INSERT INTO `users` VALUES (3, "suzy", "suzyspassword", "suzy@void.null");
INSERT INTO `users` VALUES (4, "cheryl", "cherylspassword", "cheryl@void.null");
INSERT INTO `users` VALUES (5, "monkey", "monkeyspassword", "monkey@void.null");

--------------------------------

Next you will create your connect.inc page.  For info on how to do this, click here.

Now that you have created your users table and are connected to it, we will write some code to execute a query to match a user in it.  Here is our script that will do the query:

--------------------------------

<?php

// First we set up the query as a variable to make
// it a little easier to read.
$set_up_query "select * from users where username='bob'";

// Then we execute the query
$execute_query = @mysql_query($set_up_query);

// We use the mysql_num_rows() function to see
// how many rows were returned
$number_of_rows = @mysql_num_rows($execute_query);

// Tell php that if the number of rows returned
// is more than 0 to tell us by echoing it to the
// screen
if($number_of_rows 0){
  echo 
"There were $number_of_rows matches for bob";
}else{
  
// if the number of rows was not more than 0 then
  
echo "The number of rows was $number_of_rows <-- less than 1";
}

?>


--------------------------------

Now that we know how to compare info with the database using a static name such as bob, we can do the same with variables... like this (I also modified the query structure a bit - read the comments to understand what I did):

--------------------------------

<?php

// assign the name bob to a variable called $name
$name 'bob';

// Notice this time that instead of setting up the query
// and then executing it, I just put the query inside of
// the mysql_query() function parenthesis.  It works the
// same way
$execute_query = @mysql_query("select * from users where username='$name'");

// We use the mysql_num_rows() function to see
// how many rows were returned
$number_of_rows = @mysql_num_rows($execute_query);

// Tell php that if the number of rows returned
// is more than 0 to tell us by echoing it to the
// screen
if($number_of_rows 0){
  echo 
"There were $number_of_rows matches for bob";
}else{
  
// if the number of rows was not more than 0 then
  
echo "The number of rows was $number_of_rows <-- less than 1";
}

?>


--------------------------------

I'll bet that now you are wondering how this works with a form.  Now I will just dive in and show you (Keep in mind that anything that is not in the <?php tags ?> but is in between the <!--  tags  --> is a comment in HTML):

Page:  login.php
--------------------------------

<html>
<head>
    <title>Login Script</title>
</head>

<body>

Please Sign In<br />

<!-- For the form action, I use  <?php echo $_SERVER['PHP_SELF']; ?>.  This is
       a variable for the current page name.  For example, if you look at the url for
       this page, it is pages.php.  pages.php is equal to  <?php echo $_SERVER['PHP_SELF']; ?>.
       If you want to, you can just make the action like this: action="login.php" but I don't
       reccommend it
-->

<?php
// if the form has been posted (or submitted)
if(isset($_POST['submit'])){

    // include the MySql connection script so we can check the database
    
include("connect.inc");

    
// execute the query (this is the shorter version just like above
    // (with shorter variable names))at the end of the query you can
    // see that it says " or die(mysql_error()); "
    //
    // that just means that it will execute the query, or else it will
    //die because there was dome kind
    // of error - it will print the error to tell you what was wrong
    
$r = @mysql_query("select * from users where username='{$_POST['username']}' and
        password='{$_POST['password']}'"
) or die(mysql_error());

    
// get the number of matching rows from the database
    
$n = @mysql_num_rows($r);

    
// if the number of matching rows totals more than 0
    
if($n 0){
       
// set a cookie with the users posted info
       // uname is the name of the cookie we are setting
       // $_POST['username'] is the data that was posted in the form that the
       // user submitted time()+3600 means that we are setting the cookie for
       // 3600 seconds - starting now '/' is the directory in which the cookie
       // is started at in the website
       // false means that the '/' will be for the whole website -
       // subdirectories and all.
        
setcookie("uname"$_POST['username'], time()+36000'/'false);

       
// since the number of matching rows was more than one and the cookie has been set,
       // tell the user what to do next
       
echo "You are now logged in.  <a href=your_link.php>Click Here to Continue</a>";
    }else{
       
// this else means that the number of rows returned was not greater than
       // 0.  No matching rows means that the username and password could not
       // be found in the database.
       
echo "Sorry, there was nothing in the database that matched your
            username and password combination"
;
    } 

}else{
?>

<!-- open the form -->
<form action=" <?php echo $_SERVER['PHP_SELF']; ?> " method="POST">

    <!-- Show the input text box for the username -->
    Username:  <input type="text" name="username"><br />

    <!-- Show the input text box for the password -->
    Password:  <input type="password" name="password"><br />

    <!-- Show the button to submit the form -->
    <input type="submit" name="submit">

<!-- Close the form -->
</form>

<?php
}
?>


</body>

</html>

--------------------------------

If you want to log the user out, just reverse the cookie process.  Instead of a time()+, use a time()- like this:

logout.php (create a link to this page from an already existing page):

--------------------------------

<?php

setcookie
("uname"$_POST['username'], time()-36000'/'false);

echo 
"You are now logged out.  <a href=your_link.php>Click Here to continue</a>";

?>

-------------------------------- 

This concludes this tutorial.


This page has been accessed 2,778 times     


Search Forums

Articles
PHP - Introduction..

PHP - Comments / Math..

PHP - Work With MySql..

PHP - Login/Logout Scri..

PHP - Track Traffic..

PHP - Who's Online..


Site Stats
Since July 23, 2005:
1,075,800 hits
783,208 unique visitors
Today's Info:
223 hits
74 unique visitors
More Traffic Stats

Who's Online: Active
Users: 0
Guests: 75
Truncate Online Users:

KASL Members:
Currently 2,539
Newest member: Gilues
Forum Stats:
There are 9 categories
There are 16 topics
There are 67 posts
Page Load Time
Page loaded in 0.032 secs.