Web Developers Forum & SEO Help
Web Developers ForumArticlesBlogLinks
topmenu

Programming and Scripts: Web Developers Forum

Go Back   TalkWebDev: Web Developers Forum for Web Designers & SEO Information > Web Development > Programming and Scripts
User Name
Password


Reply
 
Thread Tools Search this Thread
Old 04-06-2005, 02:47 AM   #1
Purple Haze
TalkWebDev Enthusiast
 
Join Date: Mar 2005
Posts: 37

Default Tutorial > PHP/MySQL > Creating a simple member system

This tutorial is split among four sections in this post. This is how the tutorial is organized:
1. Introduction to PHP and MySQL driven member systems
2. Setting up our MySQL database
3. The PHP side of it
4. Improving upon your newly created user management system


1. Introduction to PHP and MySQL driven member systems

Just about every other day I see someone on a forum requesting how to make a member system for their website using PHP and MySQL. What people have to realize is that there is no universal way to create a user management system; in fact, almost all systems differ in their own way because of the power of the two languages combined. The member system in this tutorial is very simple and insecure, why? Feature-rich and secure member systems are no overnight task to create. This tutorial is to show you just one way of creating one for your website and let's you take the next steps to enhance it.

Before making a member system, we need to think of a way we are going to track data from users who login. We need to have a way we can find out whether a user is logged in as well as keeping some other information about them. The four most common ways to track information are to use cookies, sessions, databases, or file writing. Cookies are text files with information given to web browsers by web servers to store on the user's computer until deleted by him or her. An expiration date can also be attached to a cookie as a date when it will automatically be deleted. A session is basically a cookie stored temporarily until the user closes his or her browser. Some online applications that have an "autologin" checkbox will use cookies for the user if the box is checked and sessions if it is not, which is one method of keeping users "logged in" even after they have left the website and closed their browsers.

The other two forms of tracking data involve storing the data on the server side. These two are the most complicated of solutions, but potentially allows more security (at least for databases) and better tracking. Commonly, keeping track of users with databases is used in conjunction with cookies, or sessions, or both. If they are not used as a combination, then the database must rely on something else to keep track of the user, such as an IP address (which is unreliable). Using databases to track session information is a common way online software is used to show a "Who's Online" page by simply selecting all active sessions in the database. File writing is the most uncommon, but is used by people who do not have the ability to use a database. One system I came across stored the logged in users as a serialized array in a file, which was constantly being written to. It is definitely the most annoying and unorganized method, but it still works.

For our system, we will be using only sessions to keep simplicity, as it is an introductory tutorial merely to get you started. We will begin by setting up our MySQL database of users, as well as inserting our admin account, followed by writing the PHP code for the member system. Finally, I will suggest some ways to take your member system a few steps further.



2. Setting up our MySQL database

Before we can do anything, we need to create our user database table and a record for the admin (your) account. Below is the SQL query you need to run to create our simple table of users. Note: for some names and variables within this script, I will be using the prefix "ph_" to differentiate them from other PHP scripts you may be running as well.

Code:
CREATE TABLE `ph_users` ( `user_id` MEDIUMINT NOT NULL AUTO_INCREMENT , `user_username` VARCHAR( 40 ) NOT NULL , `user_password` VARCHAR( 32 ) NOT NULL , PRIMARY KEY ( `user_id` ) , INDEX ( `user_username` ) );

Here is the code used to insert our admin user's username and password (which is an md5 hash of "demo") as a record in our users table.

Code:
INSERT INTO `ph_users` ( `user_id` , `user_username` , `user_password` ) VALUES ('', 'admin', 'fe01ce2a7fbac8fafaed7c982a04e229');

That's all for setting up the MySQL database, that wasn't so bad, was it?



3. The PHP side of it

The PHP code is going to consist of 3 pages within the same directory:

login.php - the login and logout page
success.php - a restricted page
common.php - common functions and methods (included on all pages)

The common.php file connects to the database, starts the session, and creates a function called login_status() used to check if a user is logged in or not. The form on login.php searched for the matching username and password in the database. If such a record exists, their session is created and they are redirected to success.php, which uses the login_status() function to determine if the user is logged in or not. Below is the code for all three files.

login.php

PHP Code:
<?php

// Start the session and require common functions
// and methods
require_once('common.php');

// This is how we are going to control error reporting
$errors = array();

switch (
$_GET['mode'])
{
    case 
'logout':
        
// Destroy session variables
        
unset($_SESSION['ph_username']);
        unset(
$_SESSION['ph_password']);

        
$errors[] = 'You have been logged out';
        break;

    case 
'login':
        
// Make sure everything is set
        
if (isset($_POST['update'], $_POST['username'], $_POST['password']))
        {
            
$md5_pass md5($_POST['password']);

            
$sql "SELECT *
                FROM ph_users
                WHERE user_username = '{$_POST['username']}'
                    AND user_password = '{$md5_pass}'"
;
            
$result mysql_query($sql);

            if (!
$row = @mysql_fetch_array($result))
            {
                
$errors[] = 'Invalid username or password';
                break;
            }

            
mysql_free_result($result);

            
$_SESSION['ph_username'] = $row['user_username'];
            
$_SESSION['ph_password'] = $row['user_password'];

            
// Redirect them upon successful login
            
header("Location: http://{$_SERVER['HTTP_HOST']}" dirname($_SERVER['PHP_SELF']) . '/success.php');
        }
        break;
}

?>

<table border="0" style="width: 20%;" cellspacing="2" cellpadding="2">
<form action="<?php echo "{$_SERVER['PHP_SELF']}?mode=login"?>" method="post">
<?php

if (sizeof($errors))
{

?>
  <tr>
    <td style="width: 100%; text-align: center" colspan="2"><?php echo implode('<br />'$errors); ?></td>
  </tr>
<?php

}

?>
  <tr>
    <td style="width: 50%"><b>Username:</b></td>
    <td style="width: 50%"><input type="text" name="username" size="40" /></td>
  </tr>
  <tr>
    <td style="width: 50%"><b>Password:</b></td>
    <td style="width: 50%"><input type="password" name="password" size="40" /></td>
  </tr>
  <tr>
    <td style="width: 100%" colspan="2">&nbsp;</td>
  </tr>
  <tr>
    <td style="width: 100%; text-align: right" colspan="2"><input type="submit" name="update" value="Login" /></td>
  </tr>
</form>
</table>

success.php

PHP Code:
<?php

// Start the session and require common functions
// and methods
require_once('common.php');

// Redirect to login if invalid authentification
if (!login_status())
{
    
header("Location: http://{$_SERVER['HTTP_HOST']}" dirname($_SERVER['PHP_SELF']) . '/login.php');
    exit;
}

// Logged in users will see this text
echo 'If you can see this text, you are logged in. Click <a href="login.php?mode=logout">here</a> to logout.';

?>

common.php

PHP Code:
<?php

// Establish a connection to the database
$db_host 'localhost';
$db_user 'username';
$db_pass 'password';
$db_name 'mydb';

if (!@
mysql_connect($db_host$db_user$db_pass))
{
    echo 
'Error, unable to connect to database!';
    exit;
}

if (!@
mysql_select_db($db_name))
{
    echo 
'Error, unable to select database!';
    exit;
}

// Start session
session_start();

// Returns bool of login status
function login_status()
{
    
$sql "SELECT *
        FROM ph_users
        WHERE user_username = '{$_SESSION['ph_username']}'
            AND user_password = '{$_SESSION['ph_password']}'"
;
    
$result mysql_query($sql);

    if (!
$row = @mysql_fetch_row($result))
    {
        return 
false;
    }

    return 
true;
}

?>



4. Improving upon your newly created user management system

You have now created your very own member system. But don't stop here, there is so much more you can do with this, here are some ideas for improving your member system:

Use a database
Make a script that will store logged in users in a separate database table. Create a field that has their last time of action and update it on every page with the current time. Every page should also include a script that deletes all sessions with a time more than 5 minutes ago from the current time. This type of user management will allow you to have a "Who's Online" page.

Better user tracking
Track a user's IP, browser, or even the page he or she is on! Keeping track of more data about each user will allow you to customize your website better based on that information.

Permissions
Create permissions that tell whether a user can view certain information or not.

Autologin
Make a checkbox for users to check when logging in to keep them logged in even after closing their web browsers.


Well, I hope you've learned from this tutorial. As always, feel free to post any comments or suggestions you may have. I will try to respond to all of them.
__________________
Sticky Icky

Last edited by Purple Haze : 04-18-2005 at 04:13 AM.
Purple Haze is offline   Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump



All times are GMT. The time now is 05:37 PM.

Powered by: vBulletin Version 3.0.7
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.

 
Admin CP Mod CP About Us Contact Us Top