PDA

View Full Version : [TUT] Multi-user login with SQL



L?KE
29-07-2008, 05:17 PM
In this tutorial I will walk you through creating a simple system by which users can register, log in and view pages that are only available to registered users. This type of system would be useful in a user system or an interactive site, but this is only a basis for bigger things. I do not recommend using this in any system like that, but as an idea of how you would go about doing this. There are many things that can be added and perhaps I will bring out a more detailed tutorial in future.

A basic knowledge of php/html is required.

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

Step 1
Creating the table

The first thing you will want to do is create a table in the database to store the user information. Open up a PMA (phpMyAdmin) and create a new databse, or in one you already have use the option to enter your own SQL code. Input the follow:




CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`username` VARCHAR(32) NOT NULL,
`password` VARCHAR(32) NOT NULL,
PRIMARY KEY (`id`)
)

Explanation:
CREATE TABLE `users` does the obvious - it creates a table named 'users'. `id` INT(11) NOT NULL AUTO_INCREMENT creates a column in the databse which is named 'id' (INT(11) means it can only be a number, max length of 11). NOT NILL means that it cannot be left empty, and AUTO_INCREMENT means that it will go up by 1 for every addition. 'username' and 'password' are the same as 'id' (new columns), difference being that they can be 32 in length and VARCHAR means they can be a selection of VARied CHARacters. PRIMARY KEY identifies that column as the unique number for each row - so no two rows will have the same id.

NOTE: The password field is 32 characters long because when we encrypt the password using md5() it creates a hash which is 32 characters long.

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

Step 2
Creating config file

Next, you'll need to make a file called config.php and use it to connect to the database. This part should need no explanation as I have commented the code enough:




<?php

//====================

$db_host = "localhost"; // The name of your SQL host
$db_name = "mysite"; // The name of your database
$db_user = "root"; // The database username
$db_pass = ""; // The database password

//====================

// Connecting to the databse
$con = mysql_connect( $db_host, $db_user, $db_pass );

// Selecting the database
$db = mysql_select_db( $db_name, $con );

// Testing if the connections were made:
if(!$con) { die("Could not connect to database."); }
if(!$db) { die("Could not select database."); }

//====================

?>

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

Step 3
Creating the register file

This is the page on which users can register. This is going to be quite hefty, so I'll give you the code and explain it after. The comments in the code refer to which part of the explanation goes with which code. register.php:




<?php

// 1
session_start();
include("config.php");

// 2
if(isset($_SESSION['logged_in'])) {

header("location: index.php");

}

// 3
if(isset($_POST['submit'])) {

// 4
$username = addslashes($_POST['username']);
$password1 = $_POST['password1'];
$password2 = $_POST['password2'];

// 5
if(empty($username) ||
empty($password1) ||
empty($password2)) {

die("You left out a field.");

} else {

// 6
if($password1 != $password2) {

die("Your passwords did not match.");

} else {

// 7
$junk = array('¬','`','!','\"','£','$','%','^','&','*','(',')','_','-','+','=','[',']','{','}',';',':','@','\'','#','~','<','>',',','.','/','?','\\','|',' ');

$new_un = str_replace($junk,"",$username);

if($new_un < $username) {

die("Your username contained invalid characters.");

} else {

// 8
$pw_len = strlen($password1);

if($pw_len < 6) {

die("Your password is too short. It needs to be 6 or more characters.");

} else {

// 9
$istaken = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `username`='" . $username . "'"));

if($istaken >= 1) {

die("That username is already being used.");

} else {

// 10
$password = md5($password1);

$create = mysql_query("
INSERT INTO `users` (
`id`,
`username`,
`password`
) VALUES (
NULL,
'" . $username . "',
'" . $password . "'
);
");

// 11
if(!$create) {

die("There was a problem creating the user.");

} else {

die("You were registered successfully. Click <a href='login.php'>here</a> to login.");

}

}

}

}

}

}

} else {

// 12

?>

<form id="register" method="post" action="<?= $_SERVER['PHP_SELF'] ?>">

Username:<br />
<input type="text" name="username" /><br /><br />

Password:<br />
<input type="password1" name="password1" /><br /><br />

Confirm Password:<br />
<input type="password2" name="password2" /><br /><br />

<input type="submit" name="submit" value="Register" />

</form>

<?php

}

?>

Explanation time!

1 - here we start the session, without this you cannot detect any sessions. We also 'include' the config file we made earlier, meaning it takes all the code from it and also meaning we dont have to connect to the database over and over!

2 - here we check is the session 'logged_in' is set. If it is, we don't want them registering, they already have an account and are logged in on it.

3 - here we see if the submit button was pressed by seeing if any fields with the name 'submit' were sent to the server. If it has been we process the input, if it hasn't we display the register form.

4 - this simply retrieves the data from the fields by their 'name' on the input tag. We store the info in suitable variables. addslashes() adds backslashes to any characters that may interrupt our SQL queries.

5 - here we see if any fields were left out. As they are all necessary we error them if ANY are empty. From this point on, we use die() as it shows the message we want and kills the rest of the script, so nothing else happens.

6 - here we see if the two passwords match. The ! asks if the opposite has happened, so by using != we see if they do NOT match.

7 - this creates an array of all the characters they are NOT allowed in their username. For the quotes " and ', you need to backslash them. After the array is created, we remove all of the junk characters from the username and compare it to the original. If there is less in the new one, we know they had invalid characters in their name.

8 - here we count the length of their password and error them if it is less than 6 characters.

9 - this part queries the database to see if there is any rows with a username that matches the one submitted, and counts how many. Then we see if the amount of rows is 1 or more (shouldn't be more, but worth a check), and if it is we tell them they cannot use that name.

10 - here is the final stage. We encrypt the password using md5(), and then insert all the details into the database.

11 - After that the query is checked if it worked, and if it hasn't it errors them, and if it has it tells them so and gives them a link to log in.

12 - This part is what would be shown if the submit button was NOT pressed. It shows a form, which I shouldn't need to explain as it is simple html. The '<?= $_SERVER['PHP_SELF'] ?>' is a simpler way of writing '<?php echo($_SERVER['PHP_SELF']); ?>', $_SERVER['PHP_SELF'] being a superglobal to determine the name of script currently executing. The '<?php } ?>' at the end simply ends the initial if/else statement to see if the submit button was pressed.

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

Step 4
Creating the login file

Same as for the register script, I'll give the code and explain after. Anything that is the same as the previous page I will not explain, no point doing it twice ^^. login.php:




<?php

session_start();
include("config.php");

if(isset($_SESSION['logged_in'])) {

header("location: index.php");

}

if(isset($_POST['submit'])) {

$username = addslashes($_POST['username']);
$password = md5($_POST['password']);

if(empty($username) ||
empty($password)) {

die("You left out a required field.");

} else {

// 1
$isreal = mysql_num_rows(mysql_query("SELECT * FROM `users` WHERE `username`='" . $username . "' AND `password`='" . $password . "'"));

if($isreal == 0) {

die("There are no users with those login details.");

} else {

// 2
$_SESSION['logged_in'] = 1;
$_SESSION['username'] = $username;

echo("<meta http-equiv='refresh' content='0;url=index.php'>");

}

}

} else {

?>

<form id="login" method="post" action="<?= $_SERVER['PHP_SELF'] ?>">

Username:<br />
<input type="text" name="username" /><br /><br />

Password:<br />
<input type="password" name="password" /><br /><br />

<input type="submit" name="submit" value="Log in" />

</form>

<?php

}

?>

Anything not commented should be described in the register script.

1 - This checks if there are any users with the inputted username AND password. If there is none, than either their username or password is incorrect.

2 - This is where they have succeded in logging in, and there are two session that are set. 'logged_in' is set to 1 (true), and 'username' is set to their username, so you can pick up who they are on the hidden pages.

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

Step 5
Creating a hidden page

The idea of this was to create a system where users can register and log in. Well if they register they are going to want to be able to access a feature that non-registered users can't, so you will need to create some pages that only they can visit. This is what is necessary on one of these pages:




<?php

session_start();

if(!isset($_SESSION['logged_in']) ||
!isset($_SESSION['username'])) {

header("location: login.php");

}

?>

<!-- Page here? -->

This basically starts the session, and checks if either of the session that are set in the login script are NOT set. If they aren't it sends 'em packing. Else, it just carries on with the page.

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

Step 6 (Final Step)
Creating a page to log them out

If users do happen to be logged in, they might want to log out. You can do this by creating a file named logout.php:




<?php

session_start();
session_destroy();

die("You have successfully logged out. <a href='login.php'>Login</a>");

?>

This is simple. Start session. Kill all sessions. Tell them they are logged out.

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

Extra;)

The reason we set a session for the username was to determine who is logged in and also if you want to perform extra queries such as updating their profile, changing password etc. This tutorial does not include scripts like these but they are a possible addition for yourself to try. I will leave you with a simple string to display the user's username:




<?php

session_start();

if(!isset($_SESSION['logged_in']) ||
!isset($_SESSION['username'])) {

header("location: login.php");

}

$username = $_SESSION['username'];

?>

Hello, <?= $username ?>! Welcome to my website.

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

That's it for now, I may add a more detailed and advance tutorial in the future, but keep in mind this is a simple tutorial, to build off of.

Farewell ;)

Thread moved to Web designing tutorials by Cheekykarl (Forum Moderator): Nice tutorial, well done.

VPSwow
29-07-2008, 05:20 PM
Wow that is amazing.
+REP

Invent
29-07-2008, 05:21 PM
Not bad :) Let's see what other comments you get and I may just move it into the tuts forum :)

Tom-743
29-07-2008, 05:24 PM
Excellent tut, and it's explained extremly well :)


Not bad :) Let's see what other comments you get and I may just move it into the tuts forum :)
Looks like its allready been moved ;)

L?KE
29-07-2008, 05:25 PM
Lol thanks for replies :)

Invent
29-07-2008, 05:28 PM
I would've waited longer for more replies, but still, wd :]

VPSwow
29-07-2008, 05:29 PM
I would've waited longer for more replies, but still, wd :]

I could tell it was Tutorial worthy ;).

Just read it a bit more in detail and its even better than when i scanned through.

L?KE
29-07-2008, 06:06 PM
Wow, better replies than i expected.

As long as it helps ;)

Zaub
30-07-2008, 10:07 AM
When I try to register, it comes up with the message:

You left out a field.

Help pls, looks like a great starter.

L?KE
30-07-2008, 12:27 PM
You need to change the register form to:


<form id="register" method="post" action="<?= $_SERVER['PHP_SELF'] ?>">

Username:<br />
<input type="text" name="username" /><br /><br />

Password:<br />
<input type="password1" name="password1" /><br /><br />

Confirm Password:<br />
<input type="password2" name="password2" /><br /><br />

<input type="submit" name="submit" value="Register" />

</form>I forgot to name the password fields accordingly :)

I would appreciate if a mod could update the first post ;)

Edited by Invent (Forum Moderator): Done :)

Zaub
31-07-2008, 12:02 PM
Also, you made an error here.. You forgot to close the tag.



<?php

session_start();
session_destroy();

die("You have successfully logged out. <a href='login.php'>Login</a>");

?>

Edited by Invent (Forum Moderator): Fixed original post :)

Meti
01-08-2008, 11:09 AM
Great tutorial!

Zaub
03-08-2008, 09:41 AM
Any chance of an editprofile code coming up soon pls? :P

L?KE
03-08-2008, 01:23 PM
Lol I'll do it now ;)

L?KE
03-08-2008, 01:49 PM
Ew, couldn't edit post :)

I can't do the edit profile script right now, as I am quite busy plus it would require me actually adding fields for the user to change :P therefore, me changing the register script too.

Excellent
03-08-2008, 01:59 PM
First of all go on your mysql database, click the SQL tab and drop this code in:

ALTER TABLE `users` (
`id` int(10) NOT NULL auto_increment,
`email` varchar(30) NOT NULL default '',
`habbo` varchar(30) NOT NULL default '',
`password ` varchar(30) NOT NULL default ",
PRIMARY KEY (`id`)
) TYPE=MyISAM;

Then call this file edit.php and put in this (not sure if it works, haven't tested it):

<?php
session_start();
include 'config.php';
if (isset($_SESSION[logged_in])) {
if (isset($_POST[update])) {
$email = addslashes(htmlspecialchars($_POST[email]));
$habbo = addslashes(htmlspecialchars($_POST[habbo]));
$password = md5($_POST[password]);
$upd = mysql_query("UPDATE users SET email = '$email', habbo = '$habbo', password = '$password' WHERE username = '$username'");
echo "Profile updated!";
}
} else {
echo "<form method='post' action='edit.php?edit'>
Email:<br>
<input type='text' name='email' size='20'><br>
Habbo name:<br>
<input type='text' name='habbo' size='20'><br>
Password:<br>
<input type='password' name='password' size='20'><br>
<input type='submit' name='update' value='Update'>";
}
?>

L?KE
03-08-2008, 02:02 PM
Cheers ;)

See, as if by magic one appeared.

Excellent
03-08-2008, 02:08 PM
No problem :) If theres some other files that need doing I'm sure me and luke will work together to put them in here :)

L?KE
03-08-2008, 02:13 PM
Of course ;)

Zaub
04-08-2008, 07:26 AM
One problem.. When I'm logged out I can see it, but when I'm not logged in it's just a blank page.

L?KE
04-08-2008, 07:14 PM
:s Not sure how that would happen. Plus I'm also not entirely sure what you meant by that :P

Zaub
05-08-2008, 07:49 AM
The form shows up, but only when I'm not logged into the system. It doesn't show up when I go to the edit profile page when I am logged into the system.

L?KE
05-08-2008, 10:01 AM
Probs something saying if the session is set don't show the form? I didn't make edit profile and didn't really read through it, so that may be it.

Zaub
06-08-2008, 07:50 AM
Figured it out.. He forgot to put the ! infront of isset.

Now that that's sorted.. It doesn't update anything.

L?KE
07-08-2008, 07:36 PM
I don't know.

You can't make a site based on this code successfully, learn to code yourself and the code will make much more sense and you can customize it a lot easier.

Hypertext
14-08-2008, 04:41 AM
Not be a bummer but in edit profile did we give up on using strings in post arrays?

Jack!
14-08-2008, 08:59 AM
can anyone set this up for me in a ZIP File i have got all the database done but i keep getting string errors and it cannot connect to database using (name) Password = yes

Fehm
14-08-2008, 08:23 PM
+rep i had to edit a little bit to get it to work fully, and added a bit more security but thats awesome =] thanks!

Jack!
26-08-2008, 10:45 AM
i put it all into a zip file for you to download i have put in 3 protected pages and an index.php with the ''Welcome to mysite''

Link:

http://www.gamehive.co.cc/site/usersystem.zip

Meti
26-08-2008, 08:05 PM
In what file should Step 5 be in?

Edit: In what file should the "extra" step be in?

Decode
26-08-2008, 08:22 PM
You put the code in step 5 at the top of the pages you have to login to view.

L?KE
04-09-2008, 07:22 PM
Yeah, as tom said.

Sorry should have specified that better?

Meti
05-09-2008, 06:40 PM
since I know nothing about PHP, you could tell us where to put what etc.

L?KE
07-09-2008, 03:59 PM
Well if the code is shown then below it, it says "Page here?" surely it is common sense to assume that the page continues below that code...

Zaub
22-09-2008, 11:00 AM
This tut has helped me expand my PHP/MySQL knowledge quite well. I'm developing a usersystem for my site with it. Cheers.

UniqueHabbo
24-09-2008, 08:07 AM
This tut has helped me expand my PHP/MySQL knowledge quite well. I'm developing a usersystem for my site with it. Cheers.
Isn't that what he said you shouldn't do?

Zaub
24-09-2008, 12:02 PM
Isn't that what he said you shouldn't do?

Huh.. So you want people to just copy and paste and ask for the code do you?

L?KE
24-09-2008, 03:36 PM
When he says "with it" I think he means his new-found php and mysql knowledge. I duno :rolleyes:

Also, didn't say you shouldn't just recommended that you didn't as it is really basic.

KyleSmith
30-01-2010, 04:18 PM
Ive created a row which is called adminlevel and i want it so people with adminlevel 1 can use the register.php only how do i do it?

L?KE
02-05-2010, 03:22 PM
I'm not guna tell you how to do it all, but here's how you'd start:



<?php

$username = $_SESSION['username'];

$select = mysql_query("SELECT * FROM `users` WHERE `username`='".$username."'");
$select2 = mysql_fetch_array($select);

$level = $select2['adminlevel'];

if($level=1 || $level='1') // I didn't know how'd you done it
{
// Show the page
} else
{
// Tell them to go and die
}

?>

Want to hide these adverts? Register an account for free!