Home > PHP > Complete advanced login member system – PHP tutorial

Complete advanced login member system – PHP tutorial

In this advanced tutorial i will teach you the steps required to create a custom build login/member system with PHP.

The system itself ofcourse has alot of room for improvements, also, it’s very easily expandable, i’ve chosen to work in a modular way, so that if you change something you only have to change it in 1 file. I’ve done this by using functions, this script is a good example of the real power of PHP.

Features:

  • Registration
  • Lost password
  • Various checks on passwords and usernames
  • users can change their password
  • Passwords are stored in a database with a seed added to it and they have sha1 encryption
  • Easy to adjust & use

Requirements:

  • Mysql database
  • a php & mysql enabled host
  • php mail() enabled host
  • ftp access to your website

Overview

Steps:

  1. Creating the mysql table
  2. Creating a db_connect.inc.php file
  3. Creating the header.php file
  4. Creating the footer.php file
  5. Creating the index.php file
  6. Creating the login.php file
  7. Creating the logout.php file
  8. Creating a function.inc.php file
  9. Creating the mail.functions.inc.php file
  10. Creating the display.functions.inc.php file
  11. Creating the login.functions.inc.php file
  12. Creating the user.functions.inc.php file
  13. Creating the validation.functions.inc.php file
  14. Creating the lostpassword.php file
  15. Creating the changepassword.php file
  16. Creating the register.php file
  17. Creating the activate.php file

Step 1: Creating the mysql table

For this tutorials i presume you already know how to add tables to your database.

Table login (SQL code):

1
2
3
4
5
6
7
8
9
10
CREATE TABLE  `login` (
  `loginid` int(10) unsigned NOT NULL auto_increment,
  `username` varchar(30) NOT NULL,
  `password` varchar(50) NOT NULL,
  `email` varchar(255) NOT NULL,
  `actcode` varchar(45) NOT NULL,
  `disabled` tinyint(1) NOT NULL default '0',
  `activated` tinyint(1) NOT NULL default '0',
  PRIMARY KEY  (`loginid`)
);

Now let us add the administrator account:

  • username: admin
  • password: yourpasswordhere

** Change the text yourpassword here with the desired password.

** Change the text youremailhere with your email adress.

SQL query:

1
insert into login (username,password,email,activated) value ('admin',sha1(concat('yourpasswordhere','0dAfghRqSTgx')),'youremailhere','1');

The table is now ready, and the administrator account has been added. let us move on to step 2.

Step 2: Creating a db_connect.inc.php file

This file will be used to manage the connection to the database.

File db_connect.inc.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
// Database settings
// database hostname or IP. default:localhost
// localhost will be correct for 99% of times
define("HOST", "localhost");
// Database user
define("DBUSER", "dbuser");
// Database password
define("PASS", "dbpass");
// Database name
define("DB", "dbname");
 
############## Make the mysql connection ###########
$conn = mysql_connect(HOST, DBUSER, PASS) or  die('Could not connect !<br />Please contact the site\'s administrator.');
 
$db = mysql_select_db(DB) or  die('Could not connect to database !<br />Please contact the site\'s administrator.');
 
?>

Let me explain:

  • HOST: this is the location for the database server it can be a hostname or an ip adress. it is usualy localhost.
  • DBUSER: this is the database user account used to access the database.
  • PASS: this is the password for the database user account.
  • DB: this is the name of the database used.

Step 3: Creating the header.php file

File header.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
error_reporting(0); // we don't want to see errors on screen
// Start a session
session_start();
require_once ('db_connect.inc.php'); // include the database connection
require_once ("functions.inc.php"); // include all the functions
$seed="0dAfghRqSTgx"; // the seed for the passwords
$domain =  "ineedtutorials.com"; // the domain name without http://www.
 
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Complete Member Login / System tutorial - <?php echo $domain; ?></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>

Step 4: Creating the footer.php file

The footer file is included at the bottom of every page, it looks like this:

1
2
3
4
<hr>
<div id='footer'>Copyright 2007-2008 &copy; <?php echo $domain; ?></div>
</body>
</html>

Step 5: Creating the index.php file

In this step we will create the homepage of the website, we’ll keep it very basic, only the login will be displayed.

File index.php:

1
2
3
4
5
6
7
8
9
<?php 
 
 require_once "header.php"; 
 //content
 include "login.php";
 // more content
 require_once "footer.php";
 
?>

Step 6: Creating the login.php file

In this step we will make the actual login page, because we want to keep it readable we create some custom build functions that will handle the actual login. So basicly all this page will do is call the functions checkLogin(), show_loginform() and isLoggedIn()

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
<?php
if (!isLoggedIn())
{
    // user is not logged in.
    if (isset($_POST['cmdlogin']))
    {
        // retrieve the username and password sent from login form & check the login.
        if (checkLogin($_POST['username'], $_POST['password']))
        {
            show_userbox();
        } else
        {
            echo "Incorrect Login information !";
            show_loginform();
        }
    } else
    {
        // User is not logged in and has not pressed the login button
        // so we show him the loginform
        show_loginform();
    }
 
} else
{
    // The user is already loggedin, so we show the userbox.
    show_userbox();
}
?>

Step 7: Creating the logout.php file

The logout file will destroy the session and it’s stored information. Afterwards it will redirect the user to the homepage.

File logout.php:

1
2
3
4
5
6
7
8
9
10
11
12
<?php 
session_start();
if( session_unregister('loginid') == true && session_unregister('username')==true ) {
    session_destroy();
	header('Location: index.php');
  } else {
   unset($_SESSION['loginid']);
   unset($_SESSION['username']);
   session_destroy();
   header('Location: index.php');
}
?>

Step 8: Creating the function.inc.php file

Now we will create a file that will store all our functions, by including this file all our functions will be accessable.
It will help keep track of your functions.

File functions.inc.php:

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
<?php
 
require_once("mail.functions.inc.php");
require_once("user.functions.inc.php");
require_once("display.functions.inc.php");
require_once("login.functions.inc.php");
require_once("validation.functions.inc.php");
 
 
function generate_code($length = 10)
{
 
    if ($length <= 0)
    {
        return false;
    }
 
    $code = "";
    $chars = "abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789";
    srand((double)microtime() * 1000000);
    for ($i = 0; $i < $length; $i++)
    {
        $code = $code . substr($chars, rand() % strlen($chars), 1);
    }
    return $code;
 
}
 
?>

Step 9: Creating the mail.functions.inc.php file

This file will contain all functions that we use to send emails.

File mail.functions.inc.php:

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
<?php
 
##### Mail functions #####

function sendLostPasswordEmail($username, $email, $newpassword)
{
 
    global $domain;
    $message = "
You have requested a new password on http://www.$domain/,
 
Your new password information:
 
username:  $username
password:  $newpassword
 
 
Regards
$domain Administration
";
 
    if (sendMail($email, "Your password has been reset.", $message, "no-reply@$domain"))
    {
        return true;
    } else
    {
        return false;
    }
 
 
}
 
function sendMail($to, $subject, $message, $from)
{
 
 
    $from_header = "From: $from";
 
    if (mail($to, $subject, $message, $from_header))
    {
        return true;
    } else
    {
        return false;
    }
    return false;
}
 
function sendActivationEmail($username, $password, $uid, $email, $actcode)
{
    global $domain;
    $link = "http://www.$domain/activate.php?uid=$uid&actcode=$actcode";
    $message = "
Thank you for registering on http://www.$domain/,
 
Your account information:
 
username:  $username
password:  $password
 
Please click the link below to activate your account.
 
$link
 
Regards
$domain Administration
";
 
    if (sendMail($email, "Please activate your account.", $message, "no-reply@$domain"))
    {
        return true;
    } else
    {
        return false;
    }
}
 
?>

Step 10: Creating the display.functions.inc.php file

This file will contain all functions that display a form or a userbox on the page.

For example: It contains the loginform, the HTML code for the userbox, the lostpassword form, …

file: display.functions.inc.php

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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<?php
 
#### Display Functions ####

function show_userbox()
{
    // retrieve the session information
    $u = $_SESSION['username'];
    $uid = $_SESSION['loginid'];
    // display the user box
    echo "<div id='userbox'>
			Welcome $u
			<ul>
				<li><a href='./changepassword.php'>Change Password</a></li>
				<li><a href='./logout.php'>Logout</a></li>
			</ul>
		 </div>";
}
 
function show_changepassword_form(){
 
echo '<form action="./changepassword.php" method="post"> 
  <fieldset> 
  <legend>Change Password</legend> 
  <input type="hidden" value="'.$_SESSION['username'].'" name="username"> 
  <dl> 
    <dt> 
      <label for="oldpassword">Current Password:</label> 
    </dt> 
    <dd> 
      <input name="oldpassword" type="password" id="oldpassword" maxlength="15"> 
    </dd> 
  </dl> 
  <dl> 
    <dt> 
      <label for="password">New Password:</label> 
    </dt> 
    <dd> 
      <input name="password" type="password" id="password" maxlength="15"> 
    </dd> 
  </dl> 
  <dl> 
    <dt> 
      <label for="password2">Re-type new password:</label> 
    </dt> 
    <dd> 
      <input name="password2" type="password" id="password2" maxlength="15"> 
    </dd> 
  </dl> 
  <p> 
    <input name="reset" type="reset" value="Reset"> 
    <input name="change" type="submit" value="Reset Password"> 
  </p> 
  </fieldset> 
</form>
';
}
 
function show_loginform($disabled = false)
{
 
    echo '<form name="login-form" id="login-form" method="post" action="./index.php"> 
  <fieldset> 
  <legend>Please login</legend> 
  <dl> 
    <dt><label title="Username">Username: </label></dt> 
    <dd><input tabindex="1" accesskey="u" name="username" type="text" maxlength="30" id="username" /></dd> 
  </dl> 
  <dl> 
    <dt><label title="Password">Password: </label></dt> 
    <dd><input tabindex="2" accesskey="p" name="password" type="password" maxlength="15" id="password" /></dd> 
  </dl> 
  <ul> 
    <li><a href="./register.php" title="Register">Register</a></li> 
    <li><a href="./lostpassword.php" title="Lost Password">Lost password?</a></li> 
  </ul> 
  <p><input tabindex="3" accesskey="l" type="submit" name="cmdlogin" value="Login" ';
    if ($disabled == true)
    {
        echo 'disabled="disabled"';
    }
    echo ' /></p></fieldset></form>';
 
 
}
 
function show_lostpassword_form(){
 
	echo '<form action="./lostpassword.php" method="post"> 
	<fieldset><legend>Reset Password</legend>
  <dl> 
    <dt><label for="username">Username:</label></dt> 
    <dd><input name="username" type="text" id="username" maxlength="30">
    </dd> 
  </dl> 
   <dl> 
    <dt><label for="email">email:</label></dt> 
    <dd><input name="email" type="text" id="email" maxlength="255">
    </dd> 
  </dl> 
  <p> 
    <input name="reset" type="reset" value="Reset"> 
    <input name="lostpass" type="submit" value="Reset Password"> 
  </p> 
  </fieldset>
</form>';
 
}
 
function show_registration_form(){
 
	echo '<form action="./register.php" method="post"> 
	<fieldset><legend>Register</legend>
  <dl> 
    <dt><label for="username">Username:</label></dt> 
    <dd><input name="username" type="text" id="username" maxlength="30">
    </dd> 
  </dl> 
  <dl> 
    <dt><label for="password">Password:</label></dt> 
    <dd><input name="password" type="password" id="password" maxlength="15">
    </dd> 
  </dl> 
  <dl> 
    <dt><label for="password2">Re-type password:</label></dt> 
    <dd><input name="password2" type="password" id="password2" maxlength="15">
    </dd> 
  </dl> 
  <dl> 
    <dt><label for="email">email:</label></dt> 
    <dd><input name="email" type="text" id="email" maxlength="255">
    </dd> 
  </dl> 
  <p> 
    <input name="reset" type="reset" value="Reset"> 
    <input name="register" type="submit" value="Register"> 
  </p> 
  </fieldset>
</form>';
 
}
?>

Step 11: Creating the login.functions.inc.php file

This file will contain the login functions

file: login.functions.inc.php

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
<?php
 
#### Login Functions #####

 
function isLoggedIn()
{
 
    if (session_is_registered('loginid') && session_is_registered('username'))
    {
        return true; // the user is loged in
    } else
    {
        return false; // not logged in
    }
 
    return false;
 
}
 
function checkLogin($u, $p)
{
global $seed; // global because $seed is declared in the header.php file
 
    if (!valid_username($u) || !valid_password($p) || !user_exists($u))
    {
        return false; // the name was not valid, or the password, or the username did not exist
    }
 
    //Now let us look for the user in the database.
    $query = sprintf("
		SELECT loginid 
		FROM login 
		WHERE 
		username = '%s' AND password = '%s' 
		AND disabled = 0 AND activated = 1 
		LIMIT 1;", mysql_real_escape_string($u), mysql_real_escape_string(sha1($p . $seed)));
    $result = mysql_query($query);
    // If the database returns a 0 as result we know the login information is incorrect.
    // If the database returns a 1 as result we know  the login was correct and we proceed.
    // If the database returns a result > 1 there are multple users
    // with the same username and password, so the login will fail.
    if (mysql_num_rows($result) != 1)
    {
        return false;
    } else
    {
        // Login was successfull
        $row = mysql_fetch_array($result);
        // Save the user ID for use later
        $_SESSION['loginid'] = $row['loginid'];
        // Save the username for use later
        $_SESSION['username'] = $u;
        // Now we show the userbox
        return true;
    }
    return false;
}
 
?>

Step 12: Creating the user.functions.inc.php file

This file will contain the user functions

file: user.functions.inc.php

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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
<?php
 
##### User Functions #####

function changePassword($username,$currentpassword,$newpassword,$newpassword2){
global $seed;	
	if (!valid_username($username) || !user_exists($username))
    {
        return false;
    }
    if (! valid_password($newpassword) || ($newpassword != $newpassword2)){
 
		return false;
	}
 
	// we get the current password from the database
    $query = sprintf("SELECT password FROM login WHERE username = '%s' LIMIT 1",
        mysql_real_escape_string($username));
 
    $result = mysql_query($query);
	$row= mysql_fetch_row($result);
 
	// compare it with the password the user entered, if they don't match, we return false, he needs to enter the correct password.
	if ($row[0] != sha1($currentpassword.$seed)){
 
		return false;	
	}
 
	// now we update the password in the database
    $query = sprintf("update login set password = '%s' where username = '%s'",
        mysql_real_escape_string(sha1($newpassword.$seed)), mysql_real_escape_string($username));
 
    if (mysql_query($query))
    {
		return true;
	}else {return false;}
	return false;
}
 
 
function user_exists($username)
{
    if (!valid_username($username))
    {
        return false;
    }
 
    $query = sprintf("SELECT loginid FROM login WHERE username = '%s' LIMIT 1",
        mysql_real_escape_string($username));
 
    $result = mysql_query($query);
 
    if (mysql_num_rows($result) > 0)
    {
        return true;
    } else
    {
        return false;
    }
 
    return false;
 
}
 
function activateUser($uid, $actcode)
{
 
    $query = sprintf("select activated from login where loginid = '%s' and actcode = '%s' and activated = 0  limit 1",
        mysql_real_escape_string($uid), mysql_real_escape_string($actcode));
 
    $result = mysql_query($query);
 
    if (mysql_num_rows($result) == 1)
    {
 
        $sql = sprintf("update login set activated = '1'  where loginid = '%s' and actcode = '%s'",
            mysql_real_escape_string($uid), mysql_real_escape_string($actcode));
 
        if (mysql_query($sql))
        {
            return true;
        } else
        {
            return false;
        }
 
    } else
    {
 
        return false;
 
    }
 
}
 
function registerNewUser($username, $password, $password2, $email)
{
 
    global $seed;
 
    if (!valid_username($username) || !valid_password($password) || 
        	!valid_email($email) || $password != $password2 || user_exists($username))
    {
        return false;
    }
 
 
    $code = generate_code(20);
    $sql = sprintf("insert into login (username,password,email,actcode) value ('%s','%s','%s','%s')",
        mysql_real_escape_string($username), mysql_real_escape_string(sha1($password . $seed))
		, mysql_real_escape_string($email), mysql_real_escape_string($code));
 
 
    if (mysql_query($sql))
    {
        $id = mysql_insert_id();
 
        if (sendActivationEmail($username, $password, $id, $email, $code))
        {
 
            return true;
        } else
        {
            return false;
        }
 
    } else
    {
        return false;
    }
    return false;
 
}
 
function lostPassword($username, $email)
{
 
	global $seed;
    if (!valid_username($username) || !user_exists($username) || !valid_email($email))
    {
 
        return false;
    }
 
    $query = sprintf("select loginid from login where username = '%s' and email = '%s' limit 1",
        $username, $email);
 
    $result = mysql_query($query);
 
    if (mysql_num_rows($result) != 1)
    {
 
        return false;
    }
 
 
    $newpass = generate_code(8);
 
    $query = sprintf("update login set password = '%s' where username = '%s'",
        mysql_real_escape_string(sha1($newpass.$seed)), mysql_real_escape_string($username));
 
    if (mysql_query($query))
    {
 
            if (sendLostPasswordEmail($username, $email, $newpass))
        {
            return true;
        } else
        {
            return false;
        }      
 
    } else
    {
        return false;
    }
 
    return false;
 
}
 
?>

Step 13: Creating the validation.functions.inc.php file

This file will contain the validation functions, these function will validate the user input to see if it’s valid and doesn’t contain any illegal characters.

file: validation.functions.inc.php

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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
<?php
 
#### Validation functions ####

function valid_email($email)
{
 
    // First, we check that there's one @ symbol, and that the lengths are right
    if (!ereg("^[^@]{1,64}@[^@]{1,255}$", $email))
    {
        // Email invalid because wrong number of characters in one section, or wrong number of @ symbols.
        return false;
    }
    // Split it into sections to make life easier
    $email_array = explode("@", $email);
    $local_array = explode(".", $email_array[0]);
    for ($i = 0; $i < sizeof($local_array); $i++)
    {
        if (!ereg("^(([A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~-][A-Za-z0-9!#$%&#038;'*+/=?^_`{|}~\.-]{0,63})|(\"[^(\\|\")]{0,62}\"))$",
            $local_array[$i]))
        {
            return false;
        }
    }
    if (!ereg("^\[?[0-9\.]+\]?$", $email_array[1]))
    { // Check if domain is IP. If not, it should be valid domain name
        $domain_array = explode(".", $email_array[1]);
        if (sizeof($domain_array) < 2)
        {
            return false; // Not enough parts to domain
        }
        for ($i = 0; $i < sizeof($domain_array); $i++)
        {
            if (!ereg("^(([A-Za-z0-9][A-Za-z0-9-]{0,61}[A-Za-z0-9])|([A-Za-z0-9]+))$", $domain_array[$i]))
            {
                return false;
            }
        }
    }
    return true;
}
 
function valid_username($username, $minlength = 3, $maxlength = 30)
{
 
    $username = trim($username);
 
    if (empty($username))
    {
        return false; // it was empty
    }
    if (strlen($username) > $maxlength)
    {
        return false; // to long
    }
    if (strlen($username) < $minlength)
    {
 
        return false; //toshort
    }
 
    $result = ereg("^[A-Za-z0-9_\-]+$", $username); //only A-Z, a-z and 0-9 are allowed
 
    if ($result)
    {
        return true; // ok no invalid chars
    } else
    {
        return false; //invalid chars found
    }
 
    return false;
 
}
 
function valid_password($pass, $minlength = 6, $maxlength = 15)
{
    $pass = trim($pass);
 
    if (empty($pass))
    {
        return false;
    }
 
    if (strlen($pass) < $minlength)
    {
        return false;
    }
 
    if (strlen($pass) > $maxlength)
    {
        return false;
    }
 
    $result = ereg("^[A-Za-z0-9_\-]+$", $pass);
 
    if ($result)
    {
        return true;
    } else
    {
        return false;
    }
 
    return false;
 
}
 
?>

Step 14: Creating the lostpassword.php file

When the user lost his password he can request a new temporary password. He has to enter his username and his password, if they are correct his password will be reset to a radom generated password and an email will be sent containing this new password, the user can use this password to login and change its password.

file: lostpassword.php

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
<?php
 
require_once "header.php"; 
 
if (isset($_POST['lostpass'])){
 
	if (lostPassword($_POST['username'], $_POST['email'])){
 
		echo "Your password has been reset, an email containing your new password has been sent to your inbox.<br />
		<a href='./index.php'>Click here to return to the homepage.</a>
		";
 
	}else {
 
		echo "Username or email was incorrect !";
		show_lostpassword_form();
 
	}
 
} else {
	//user has not pressed the button
	show_lostpassword_form();	
}
 
 require_once "footer.php";
?>

Step 15: Creating the changepassword.php file

On this page the user can change his password, ofcouse he has to be logged in first. He will also have to enter his old password.

file: changepassword.php

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
<?php
 
require_once "header.php";
 
if (isLoggedIn() == true)
{
 
    if (isset($_POST['change']))
    {
 
        if (changePassword($_POST['username'], $_POST['oldpassword'], $_POST['password'],
            $_POST['password2']))
        {
            echo "Your password has been changed ! <br /> <a href='./index.php'>Return to homepage</a>";
 
        } else
        {
            echo "Password change failed! Please try again.";
            show_changepassword_form();
        }
 
    } else
    {
        show_changepassword_form();
    }
 
} else {
	// user is not loggedin
    show_loginform();
}
 
require_once "footer.php";
 
?>

Step 16: Creating the register.php file

On this page users can create an account.

file: register.php

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
<?php
 
require_once "header.php"; 
 
if (isset($_POST['register'])){
 
	if (registerNewUser($_POST['username'], $_POST['password'], $_POST['password2'], $_POST['email'])){
 
		echo "Thank you for registering, an email has been sent to your inbox, Please activate your account.
		<a href='./index.php'>Click here to login.</a>
		";
 
	}else {
 
		echo "Registration failed! Please try again.";
		show_registration_form();
 
	}
 
} else {
// has not pressed the register button
	show_registration_form();	
}
 
 require_once "footer.php";
?>

Step 17: Creating the activate.php file

On this page users can activate their account.

file: activate.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
 
require_once "header.php";
 
$uid = (int)htmlentities(strip_tags($_GET['uid']));
$actcode = htmlentities(strip_tags($_GET['actcode']));
 
if (activateUser($uid, $actcode) == true)
{
    echo "Thank you for activating your account, You can now login.
		<a href='./index.php'>Click here to login.</a>";
} else
{
    echo "Activation failed! Please try again.";
    echo "If problem presists please contact the webmaster.";
}
 
require_once "footer.php";
?>
  1. Manu
    January 13th, 2009 at 13:02 | #1

    Could not connect !
    Please contact the site’s administrator.

    it changes with forms you explain and it continues giving the same error to me, it helps please, mandame an example mail if you are so amiable. or this script php is erroneous

  2. Manu
    January 13th, 2009 at 13:03 | #2

    Could not connect !
    Please contact the site’s administrator.

    it changes with forms you explain and it continues giving the same error to me, it helps please, mandame an example mail if you are so amiable. or this script php is erroneous

  3. DynamiteN
    January 17th, 2009 at 14:53 | #3

    hi.
    tried this and it works perfect, but i am working on a site where i want a particular section to be all for admin or VIP and so on .. wa wondering how i can do so that i can have admin and s on … i need to add something to db ? or maybe in php … ? …. relly do need to know it does work great otherwise…

  4. h
    January 18th, 2009 at 22:35 | #4

    Hi @DynamiteN you can add in the login table… an attribute that saves the kind of user. For example… admin = 1 , user = 2. When you logged in, you evaluate which kind of user it is trying to access. In this way, you can redirect to different pages!
    Happy programming

  5. h
    January 18th, 2009 at 22:36 | #5

    @manu.. you are not saying the things clear… PLEASE be specific

  6. Manu
    January 19th, 2009 at 15:15 | #6

    said hello, I

    I get this ruling,
    Could not connect!
    Please contact the site’s administrator.
    where I have to work to put the record in the database.
    and if I can help send a login system completro co redirecion counter sela mail to activate your account, I hope you can help me thank you
    Note: If your services can pay for your work would be a pleasure, and also thank you, to teach people like us who started in this field dificl php.
    thanks again mafey_fc@hotmail.com

  7. h
    January 19th, 2009 at 17:00 | #7

    @manu which mysql front-end are you using ?

  8. DynamiteN
    January 19th, 2009 at 19:53 | #8

    @h
    k ..
    but what is it i then would add in the db ,
    i mean ,
    if i add in to the login table something like “levelid” or just “admin” then what is it i shall put in the fields ? .. i use phpmyadmin to acces my db.

    the experince is less then php for me …
    would really appreciate the help ….

    //DynamiteN

  9. h
    January 20th, 2009 at 17:34 | #9

    @DynamiteN suposse that somebody else is gonna register the vip or admin people right ?
    in that case you’ll have to put something like this

    insert into login (username,password,email,activated, type) value (‘mamma’,sha1(concat(‘mypassword’,'0dAfghRqSTgx’)),’mamma@info.com’,'1′, ‘1′);

    In this case you’ll know that 1 is admin, if you register a normal user it will be like this

    insert into login (username,password,email,activated, type) value (‘noob’,sha1(concat(‘1234567′,’0dAfghRqSTgx’)),’noob@info.com’,'1′, ‘0′);

    In the other hand 0 will be by the others users!

    You can use the same page of registering. You only pass a variable in the link that you know that you are registering normal users or vip. For example http://www.yoursite.com/index.php?register=1

    If it is says 1 it will process the first query but if register=0 it will be the normal registration. Please let me know if you need help!

    cheers~

  10. Sathiya Narayanan
    January 26th, 2009 at 11:49 | #10

    hi i am new to php and website development.
    CAN U PLEASE HELP ME IN RUNNING THIS CODE IN MY COMPUTER LOCALHOST???????

    i tried but it shows some error and displays Could not connect !
    Please contact the site’s administrator.

  11. h
    January 27th, 2009 at 17:56 | #11

    @Sathiya Narayanan which server are you running? IIS or Apache?

  12. Sathiya Narayanan
    January 30th, 2009 at 05:37 | #12

    @h : Apache……..

  13. craig
    January 31st, 2009 at 18:45 | #13

    its it work

  14. Sathiya Narayanan
    February 2nd, 2009 at 09:50 | #14

    Dude please help…… i am developing a online library system.
    i need this module desperately……… please tel how to run
    this code in apache server(local host).

  15. h
    February 2nd, 2009 at 18:05 | #15

    @Sathiya Narayanan when you say could not connect? You are talking about the db ? please display the errors…

  16. K.Sathiya Narayanan
    February 4th, 2009 at 05:03 | #16

    “Could not connect !
    Please contact the site’s administrator.” get this error at first page itself

  17. Bob
    February 6th, 2009 at 03:11 | #17

    Fatal error: Function name must be a string in /home/gamers/public_html/login.php on line 2

    I keep getting that error and the rest of my pages are white but the footer???

    Help please???

  18. Bob
    February 6th, 2009 at 15:48 | #18

    ?php require_once(“mail.functions.inc.php”); require_once(“user.functions.inc.php”); require_once(“display.functions.inc.php”); require_once(“login.functions.inc.php”); require_once(“validation.functions.inc.php”); function generate_code($length = 10) { if ($length <= 0) { return false; } $code = “”; $chars = “abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ123456789″; srand((double)microtime() * 1000000); for ($i = 0; $i

    I keep getting this on everypage now and still login.php is messed up still.

  19. h
    February 6th, 2009 at 16:20 | #19

    @Sathiya Narayanan hello, have you checked your config file ??:P

  20. February 7th, 2009 at 15:35 | #20

    Hi,

    I tried and tested your complete member log in script and its very powerful however i have something to add the following:

    1. I want to add firstname, lastname and phone number, i tried to edit the script and add rows in the table but it doesn’t work.

    2. After the activation, it will redirect to a certain site.
    3. When the user activated the account, and when he clisk it for the 2nd time it will redirect to a certain site instead of echoing “you already subscribe”

    Best regards,

    Robert

  21. heliver
    February 23rd, 2009 at 13:47 | #21

    Hi,

    No blank screen but I have this error,
    Parse error: parse error in D:\WWW\Login\user.functions.inc.php on line 73

  22. heliver
    February 23rd, 2009 at 13:59 | #22

    Hi,

    No blank screen but I have this error,
    Parse error: parse error in D:\WWW\Login\user.functions.inc.php on line 73

    71: global $seed;
    72: if (!valid_username($username) || !valid_password($password)
    73: !valid_email($email) || $password != $password2 || 74:user_exists($username))

  23. santhosh
    February 25th, 2009 at 15:07 | #23

    Hi need php projects to do practice on php. Any site is available to get a free projects….or any one have projects on php , PLEASE send to this mail id: santhosh_247@yahoo.co.in

  24. Cliff
    March 4th, 2009 at 14:20 | #24

    Hi There
    I have spent hours trying to get this to work, I think by now I’ve lost the plot.

    Can you please help!!

    When you enter your correct username and password press the login button how do I get it to go to a page say welcome.php

    Also how to protect my existing pages.

    Many Thanks
    Cliff

  25. March 9th, 2009 at 11:35 | #25

    Hello,

  26. March 9th, 2009 at 11:43 | #26

    Hello,
    I’m new to webdesign and and also to php and mysql. Can you please advise if this script has a remember me tick box also what kind of password protection does this use?? Not sure if I read anythin on password protection.

    I have a script already that has a 32bit md5() password encryption and also the use of sha1() 40bit encryption to generate a 40 digit hash that is used for the activation code, what this script does not ahve is a cookie to remember me function. ALso not sure if the script works as I have not been able to test it as am not familiar with working with localhost yet. If anyone can help they can contact me on my email kaise@hotmail.co.uk.

    Thank You and any help will be much appreciated.

  27. Christine
    March 10th, 2009 at 18:09 | #27

    Excellent code :) … I am getting everything to work except I can’t register… it keeps saying registration is failed, but I did get my admin account to work…

    Any ideas?

  28. Christine
    March 10th, 2009 at 21:20 | #28

    scratch my last post…i got the registration to work, but I actually need to add critera to the registration and I’m not sure how to do it. I added it to the HTML, but when i enter information in when I register, it doesn’t go through to my database (mysql), where else do I need to edit the feilds.

  29. Vivek
    March 13th, 2009 at 10:54 | #29

    Amazing!! Can’t thank you enough for this, very detailed, very helpful!!

    Cheers!! …Vivek

  30. March 24th, 2009 at 17:12 | #30

    I would love to get this code working correctly. We host our own web server and need this for our clients to login. Looking for a way to protect the clients page using this code. Can anyone help? I got the code somewhat working. Not sure how to protect my clients page so that they need to login to view it. do I place a login code at the top of my client page?

    Omar operez@b-g-s.com

  31. john k
    March 25th, 2009 at 16:46 | #31

    I am getting this message when i use my browser to go to index page

    Fatal error: Call to undefined function isloggedin() in /home/traffic2/public_html/insane/login.php on line 2

    Any Ideas / Suggestions ???

  32. john k
    March 25th, 2009 at 17:10 | #32

    never mind lol I see I have to include some files sorry. So far this seems excellent !

  33. wtf
    March 28th, 2009 at 01:38 | #33

    terrible

  34. iain
    March 28th, 2009 at 02:28 | #34

    Gertjan, you rock hard! Excellent tut.
    One small amend, line 102 (user.functions.inc.php) is missing the or operator between password and email
    (my text editor picked it up).
    Thanks so much for sharing.

  35. pronek
    March 29th, 2009 at 12:57 | #35

    HELP – When I wont add admin I have this:
    #1064 – Something is wrong in your syntax next to ‘value (‘admin’,sha1(concat(‘yourpasswordhere’,'0dAfghRqSTgx’)),” in line 1

  36. sjoerd
    March 30th, 2009 at 15:44 | #36

    Looks like you’re mixing up single quotes (‘) and left/right quotes (` and ’). Just make sure all your quotes are the ordinary single quote (‘) and then try again.

  37. Abraham
    April 2nd, 2009 at 14:28 | #37

    Anyone! Please help me, i need to no how to do a error message to show to the user when they have type wrong in activate form.

  38. Goodwine
    April 14th, 2009 at 17:53 | #38

    nice, many people is complaining, but I think it is a good tutorial which can be easily fixed, at least this gave me an idea
    thanks :)

  39. April 14th, 2009 at 20:27 | #39

    WORKS GREAT!

    But this may just be my problem, where does the script register variables into the SESSION? I’m trying to register another field that I added to the table. “avatar”, I just can’t seem to find it.

  40. erik
    April 23rd, 2009 at 09:52 | #40

    ok im totaly new here bought a site yesterday so..
    and now i want a log in system so ive tried to dos omething etc but now i get this error..

    Please contact the site\’s administrator.’); $db = mysql_select_db(DB) or die(‘Could not connect to database !
    Please contact the site\’s administrator.’); ?>

    could you help me??
    im getting this by selecting the .php file on my site

  41. karl
    April 23rd, 2009 at 20:56 | #41

    yo tengo que hacer el formulario??????

  42. April 28th, 2009 at 03:23 | #42

    I must say, Great Tutorial. I can understand why people are getting blank pages after they set up the site. I’ve had the same thing happen to me, but I was able to fix it. When the user clicks view code for the user.functions.inc.php, there is something missing in the registerNewUser function. There needs to be another || after !valid_password($password) on line 101. After adding that or operator (||), your project should work, that’s if you followed the rest of the tutorial how it is supposed to be followed.

  43. Daan
    April 28th, 2009 at 10:43 | #43

    Its works great, but got an problem…

    When I try to register. I fill in te form and sumbit te register button.

    I get the message: “Registration failed! Please try again.”

    But when I take a look in me database, I see the username password and email I just had enterd in the registration form.

    whats wrong with the code? I just copied the whole code above here. and tested if the code worked correctly.

    Don’t know what to do now.!

  44. April 29th, 2009 at 05:02 | #44

    Excellent code :) … I am getting everything to work except I can’t register! it keeps saying registration is failed! i been copy all the code above.. what would be wrong? plz email me if you read this i really actually need this to my login system school project! dmokil22@yahoo.com email me plss.

    Any ideas?

  45. MHz
    May 5th, 2009 at 11:11 | #45

    How to specify another target for lostpassword and the other thing like activation. I am using PHP tables, so I get a url like this: index.php?page=lostpass , how to set the target to ‘index.php?page=lostpass’? Thanks

  46. MHz
    May 5th, 2009 at 11:19 | #46

    I just found it in ‘display.functions.inc.php’, but when I change the ACTION variable to ‘index.php?page=lostpw’ I get this error: ‘
    Fatal error: Call to undefined function lostpassword() in …/lostpassword.php on line 7′ Can this be solved? Thanks

  47. MHz
    May 5th, 2009 at 11:41 | #47

    In the mean time I kept searching for a solution and now everything works accept one thing. When I login and click the changepassword link, I get the login form because there is no sessions. Why?

  48. balazscsaba2006
    May 6th, 2009 at 13:19 | #48

    Hy all!
    i don’t know how Christine made the registration not to fail, ’cause no matter what i do, i just can’t log in!
    …why???
    please help
    appreciate it

  49. balazscsaba2006
    May 6th, 2009 at 14:08 | #49

    pffff…no i managed to get the login to work, i can log in, but the script doesn’t send mail. i deleted the extra “return false” from the sendMail function, but still isn’t sending a mail…i ahve no clue why :)
    please help me!!!

  50. Heeeelp!!
    May 7th, 2009 at 00:20 | #50

    When I go to my register page nothing appears on the screen! It is just blank. I checked my connect file and everything is correct! Help!!!!????

Comment pages
  1. January 17th, 2008 at 22:00 | #1
  2. February 5th, 2008 at 16:16 | #2
  3. June 30th, 2008 at 10:36 | #3