Forgot Password / Register
Site Statistics
Total Members: 520
Total Tutorials: 242
Newsest User: 8884244477
Todays Unique Hits: 431
0 Users 2 Guests Online

User System (Part 1)

Please read the comments in this tutorial.

Features:

  • Encrypted passwords
  • Email Validation
  • Change Password
  • Members List
  • User Profiles


Ok lets start of with the SQL.

Run this query
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
CREATE TABLE `members` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(30) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(55) NOT NULL,
`location` varchar(40) NOT NULL default 'N/A',
`userlevel` int(3) NOT NULL default '1',
`age` int(3) NOT NULL,
`sex` varchar(40) NOT NULL default 'N/A',
PRIMARY KEY (`id`)
) TYPE=MyISAM;
 
CREATE TABLE `verification` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(30) NOT NULL,
`code` varchar(255) NOT NULL,
PRIMARY KEY (`id`) 
) TYPE = MYISAM ;

Now we have the SQL lets start with the user system.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<? 
session_start(); // Start new or resume existing session
 
$conn = mysql_connect("localhost","USER","PASSWORD");  // Connect to local MySQL database with username and password
mysql_select_db("DBNAME") or die(mysql_error()); //Select which database to use
 
// Query database for account details if they exist and store them in the $logged variable
$logged = mysql_fetch_array(mysql_query("SELECT * FROM `members` WHERE `id` = '".$_SESSION['id']."' AND `password` = '".$_SESSION['password']."'")); 
 
// Some variables returned by the server, no need to edit these
$host = $_SERVER['HTTP_HOST'];
$self = $_SERVER['PHP_SELF'];
 
// Update the following to reflect your site name
$sitename = "My Site";
 
// Email activation. 1 = true, 0 = false
$semail = "1";
?>

Change the connection and change your site name.

Now lets let people register

register.php Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
session_start(); // Start new or resume existing session
include "config.php";
 
if(isset($_GET['verify'])) { // 'verify' variable defined in the URL ($_GET), so must be trying to activate account
 
    $code = mysql_real_escape_string($_GET['code']); // Escapes special characters for the verification code
 
    $getcode = mysql_query("SELECT * FROM `verification` WHERE `code` = '".$code."'");
    if(mysql_num_rows($getcode) == 0) { // Verification code doesn't exist in the database 
        echo "Invalid verification code!"; 
    } else { // Verification code exists
        $userdata = mysql_fetch_array($getcode);
        $update = mysql_query("UPDATE `members` SET `userlevel` = '2' WHERE `username` = '".$userdata['username']."'"); // Set account to 'userlevel', which means they can now login to their account
        $delete = mysql_query("DELETE FROM `verification` WHERE `code` = '".$code."'"); // Remove the verification code from the database
        echo "Thank you, Your account has been verified.";
    }
 
} else if(isset($_GET['register'])) { // The register form has been submitted, lets create a user
 
    if((!$_POST['username']) || (!$_POST['password']) || (!$_POST['cpassword']) || (!$_POST['email'])) { // Check no fields are blank
        echo "A field was left blank please go back and try again.";
    } else {
        $username = mysql_real_escape_string($_POST['username']); // Escapes special characters for the username
        if($_POST['password'] == $_POST['cpassword']) { // Check to see both passwords match
            $password = md5($_POST['password']); // Encrypt the password 
            $cname = mysql_query("SELECT `username` FROM `members` WHERE `username` = '".$username."'"); // Check to see if an account with that username is already in use
            if(mysql_num_rows($cname) >= 1) { // If account with username already exists then do not continue
                echo "The username is already in use"; 
            } else { // Username does not exist, OK to continue
                $email = mysql_real_escape_string($_POST['email']); // Escapes special characters for email input
                if($semail == "1") { // $email set as 1 means email activation is active
                    mysql_query("INSERT INTO `members` (`username`, `password`, `email`) VALUES('".$username."','".$password."','".$email."')"); // Insert the account into the members database
                    $code = substr(str_shuffle("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 0, 16); // Generate a random 16 character code
                    mysql_query("INSERT INTO `verification` (`username`, `code`) VALUES('".$username."','".$code."')"); // Insert the generated code into the 'verification' table
                    $link = "http://$host$self?verify&code=$code"; // Link what the user will use to activate their account
 
                    // Send an email to the user contain the link required to activate their account
                    mail("$email", "Member-Ship Validation", "Thank you for registering on ".$sitename.".
                    Please copy the below link into you address bar,
 
                    ".$link, "From: Site Verification");
 
                    echo "You are now registered,Please check your email to activate your account.";
                } else { // Email activation is disabled, just create an active account
                    mysql_query("INSERT INTO `members` (`username`, `password`, `email`, `userlevel`) VALUES('".$username."','".$password."','".$email."','2')"); // Insert the account into the members database
                    echo "You are now registered,You can now loggin to your account";
                }
            }
        } else {
            echo "Your password and conformation password do not match!";
        }
    }
 
} else { // Show the register form
 
    echo "<form action='register.php?register' method='post'>
        <table>
          <tr>
            <td>Username:</td>
            <td><input type='text' name='username' size='30'</td>
          </tr>
          <tr>
            <td>Password:</td>
            <td><input type='password' name='password' size='30'></td>
          </tr>
          <tr>
            <td>Confirm Password:</td>
            <td><input type='password' name='cpassword' size='30'></td>
          </tr>
          <tr>
            <td>Email:</td>
            <td><input type='text' name='email' size='30'></td>
          </tr>
          <tr>
            <td colspan='2'><input type='submit' value='Register'></td>
          </tr>
        </table>
    </form>";
 
}
?>

Now people can register lets let them login

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
session_start(); // Start new or resume existing session
include "config.php";
 
if($logged['id']) { // User is already logged in to their account
 
    echo "Welcome ".$logged['username'].""; // Welcome and show the Username currently logged in
    echo "- <a href='editprofile.php'>Edit Profile</a>
          - <a href='changepassword.php'>Change Password</a>
          - <a href='members.php'>Members</a>
          - <a href='logout.php?logout'>Logout</a>";
 
} else if(isset($_GET['login'])) { // 'login' variable defined in the URL ($_GET), so must be trying to login to their account
 
    $username = mysql_real_escape_string($_POST['username']); // Escapes special characters for the username
    $uinfo = mysql_query("SELECT * FROM `members` WHERE `username` = '".$username."'"); // Retrieve the user from the database with the Username
    if(mysql_num_rows($uinfo) == '0') {
        echo "Username not found";
    } else {
        $udata = mysql_fetch_array($uinfo); // Retrieve the account from the table
        if($udata['userlevel'] == "1") { // Check the 'userlevel' of the account (1=not verified, 2=verified)
            echo "This account had not been verified.";
        } else if($udata['password'] == md5($_POST['password'])) {
            $user = mysql_fetch_array(mysql_query("SELECT * FROM `members` WHERE `username` = '".$username."'")); 
            $_SESSION['id'] = $user['id'];
            $_SESSION['password'] = $user['password'];
            echo "You are now logged in, Please wait. . .";
            echo "<meta http-equiv='Refresh' content='2; URL=login.php'/>"; // Use a meta refresh to redirect them in 2 seconds
        } else { // Password submitted does not match the one in the database
            echo "Incorrect username or password!"; 
        }
    }
 
} else { // If no one is logged in or trying to login, then show the login form
 
    echo "<form action='login.php?login' method='post'>
        <table>
          <tr>
            <td>Username:</td>
            <td><input type='text' name='username'></td>
          </tr>
          <tr>
            <td>Password:</td>
            <td><input type='password' name='password'></td>
          </tr>
            <tr>
            <td colspan='2'><input type='submit' value='Login'></td>
          </tr>
        </table>
    </form>";
 
}
?>

Now lets make the logout page

1
2
3
4
5
6
7
8
9
10
11
<?php
session_start(); // Start new or resume existing session
include "config.php";
if(isset($_GET['logout'])) { // 'logout' variable defined in the URL ($_GET), so must be trying to logout of their account
 
    unset($_SESSION['id']); // Unsets the session
    unset($_SESSION['password']); // Unsets the session
    echo "You are now logged out.";
 
}
?>

Now lets display all the members

members.php Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
session_start(); // Start new or resume existing session
include "config.php";
if(isset($_GET['user'])) { // 'user' variable defined in the URL ($_GET), so must be trying to view an account
 
    $username = mysql_real_escape_string($_GET['user']); // Escapes special characters for the username
    $getuser = mysql_query("SELECT * FROM `members` WHERE `username` = '".$username."'");
    if(mysql_num_rows($getuser) == 0) { // Account not found in database with that username
        echo ("User Not Found"); 
    } else { // Account exists in database so show their profile
        $user = mysql_fetch_array($getuser); 
        echo "<b>".$user['username']."'s Profile</b>
        Email: ".$user['email']."
        Location: ".$user['location']."
        Sex: ".$user['sex']."
        Age: ".$user['age'];
    }
 
} else { // Show directory of members
 
    $getusers = mysql_query("SELECT * FROM `members` ORDER BY `id` ASC"); 
    while ($user = mysql_fetch_array($getusers)) { // Display all acounts in database
        echo "<a href='members.php?user=".$user['username']."'>".$user['username']."</a>"; 
    }
 
}
?>

Now we will make them able to edit there profile

editprofile.php Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
session_start(); // Start new or resume existing session
include "config.php";
 
if($logged['id']) { // User is already logged in to their account
    if(isset($_GET['update'])) { // 'update' variable defined in the URL ($_GET), so must have submitted the form
 
        $email      = mysql_real_escape_string($_POST['email']); // Escapes special characters for the user's email
        $location   = mysql_real_escape_string($_POST['location']); // Escapes special characters for the user's location
        $age        = (int)$_POST['age']; // Turns the user's age into a integer
        $sex        = mysql_real_escape_string($_POST['sex']); // Escapes special characters for the user's gender
        mysql_query("UPDATE `members` SET `email` = '".$email."', `sex` = '".$sex."', `age` = '".$age."', `location` = '".$location."' WHERE `username` = '".$logged['username']."'");
        echo "Profile updated!";
 
    } else {
        $user = mysql_fetch_array(mysql_query("SELECT * FROM `members` WHERE `username` = '".$logged['username']."'"));
        echo "<form action='editprofile.php?update' method='post'>
            Email: <input type='text' name='email' value='".$user[email]."'>
            Location: <input type='text' name='location' value='".$user[location]."'>
            Age: <input type='text' name='age' value='".$user[age]."'>
            Sex: <select name='sex' value='".$user[sex]."'>
            <option value='Male' "; 
            if($user['sex'] == "Male") { echo "selected"; } 
            echo ">Male</option> 
            <option value='Female' "; 
            if($user['sex'] == "Female") { echo "selected"; } 
            echo ">Female</option>
            </select>
            <input type='submit' value='Update'>
        </form>";
    }
} else { // If no one is logged in or trying to login, then show a warning
 
    echo "You are not logged in.";
 
}
?>

Last thing in this tutorial is to let them change there password

changepassword.php Copy to clipboard
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?php
session_start(); // Start new or resume existing session
include "config.php";
 
if($logged['id']) { 
    if(isset($_GET['update'])) { // 'update' variable defined in the URL ($_GET), so must be trying to submit the form
 
        if($logged['password'] == md5($_POST['oldpassword'])) { // If the 'Old Password' field matches their current password then continue
            if($_POST['newpassword'] == $_POST['cnewpassword']) { // Check that the password and confimation password match
                $newpassword = md5($_POST['newpassword']); // Encrypt the password 
                mysql_query("UPDATE `members` SET `password` = '".$newpassword."' WHERE `username` = '".$logged['username']."'"); // Update the password
                echo "Password Updated, You will need to relogin with your new password.";
                unset($_SESSION['id']); // Unset the session to make them need to login again
                unset($_SESSION['password']); // Unset the session to make them need to login again
            } else {
                echo "Your new password and conformation password do not match!";
            }
        } else {
            echo "Your old password does not match the database password!";
        }
 
    } else { // Form hasn't been submitted, so show it
 
        echo "<form action='changepassword.php?update' method='post'>
            Old Password: <input type='password' name='oldpassword'>
            New Password: <input type='password' name='newpassword'>
            Confirm Password: <input type='password' name='cnewpassword'>
            <input type='submit' value='Change'>
        </form>";
 
    }
} else { // If no one is logged in or trying to login, then show a warning
 
    echo "You are not logged in.";
 
}
?>
DanielXP
Author:
Views:
31691
Rating:
Posted on Thursday 19th March 2009 at 04:38 PM
Paul
Paul
i keep getting this error message when i login

Access denied for user 'sthelensclubberz'@'localhost' (using password: NO)
Posted on Monday 16th March 2009 at 04:19 PM
ShadowMage
ShadowMage
Don't need to go that far into the system if you only want basics, without SEO. but hey, it could be nice. I know I use it all the time on my sites.
Posted on Saturday 14th March 2009 at 07:41 PM
angieluckyd
angieluckyd
Hey why dont you just use mod_rewrite??
Posted on Thursday 12th March 2009 at 04:58 PM
Angelus
Angelus
what tutorial? can you give me a link? :)
Posted on Thursday 12th March 2009 at 03:18 PM
ShadowMage
ShadowMage
There is a tutorial on here in which I submitted in the PHP section for a MySQL OOP Class. there should be a protect function in there you can use.
Posted on Thursday 12th March 2009 at 06:51 AM
Angelus
Angelus
I found 1 tutorial but it isnt for sql injections..
Where can i found tutorial for sql injections, because i really want to use this script... :)
Posted on Thursday 12th March 2009 at 12:18 AM
ShadowMage
ShadowMage
This is pretty safe. There are better ways to secure it but this is basic ;) I might make a tutorial or two on how to prevent SQL Injections and some other things =]
Posted on Wednesday 11th March 2009 at 09:41 PM
Angelus
Angelus
thanks :)
I'm web design coder and i know only some things about security, so can you please tell how safe is this script for example hacker attacks?
Posted on Thursday 26th February 2009 at 08:54 PM
sean04
sean04
thanks for the tip mod-shadow. i checked that out but everything was fine.

i looked around and the problem was i had html tags with the php and yea it was a mess :P
Posted on Thursday 26th February 2009 at 04:14 PM
ShadowMage
ShadowMage
Seems to me that the profile.php page is not getting the config.php

Also, for FireFox check the preferences to make sure it is not blocking meta redirects or meta redirects. Generally, if you have the web developer toolbar it blocks it but i'm not to sure. I use firefox at home and when I decide to use a meta refresh it always seems to work.