webmasters.icecaves.net -  - Blog -  -  -  -  - Forums
Hello, Guest! - Register -
ArticlesHTML & CSS ScriptsJavaScript ScriptsPHP ScriptsForums Index Feb 9,  PST
How to Create a Simple Login System with PHP and MySQL
Written by: Icy | How to create a simple login system including how to create the database, login and logout page, and the registration pages.
  Mxx Digg StumbleUpon  

In this article/tutorial, I'll be teaching you how to make a simple login system.
First, make a database. I called mine login. Now, run this into SQL on your database. Or you can do it manually.

Code:
CREATE TABLE `users` (
`id` INT( 4 ) NOT NULL AUTO_INCREMENT ,
`username` VARCHAR( 30 ) NOT NULL ,
`password` VARCHAR( 32 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM



You can edit some stuff, like the limit of how much the username can be, and password, but we're using MD5 encryption for security, so leave it at a reasonable size.

If you want, you can add a test account manually, by running this into SQL.

Code:
INSERT INTO `users` VALUES (1, 'test', 'abc123';


The connection page

Okay, now we need to create a connection page, create a file called connection.php. Paste the following code on this page.

Code:
<?

//start the session
session_start();

//connect to database
$error = "Could not connect.";
mysql_connect('localhost','username','password') or die($error);
mysql_select_db('db_name') or die($error);

?>


Edit the username to your MySQL user, (If you don't know how to create one, ask your host or PM me.) password to your MySQL user's password, and db_name to the databases name. Here's my example.


Code:
$error = "Could not connect.";
mysql_connect('localhost','finale_user','testpw') or die($error);
mysql_select_db('finale_login') or die($error);


As you can see, I put my MySQL user and password, and the database name.

For more help on MySQL users, ask your host, or PM me or Haily.
NOTE: After creating the MySQL user, you will have to add it to the database login, or the database you are using for this script won't work.
This part is very important in the script, please leave it in every page if it's there.


The register page

Make a new file and call it register.php. Then paste the following code on that page.

Code:
<?php

include 'connection.php';

if ($_POST['register'])
{
//this is to get the form data
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);

// To protect from MySQL injection.
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

if (!$username||!$password)
echo "Registration not complete , please fill out all fields.";
else
{
//encrypt password for extra security
$password = md5($password);

//this is to check if username already taken/in the database
$check = mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($check)>=1)
echo "Username already taken";

else
{
//register into database
$register = mysql_query("INSERT INTO users VALUES ('','$username','$password')");
echo "You have been successfully been registered! Click <a href='login.php'>here</a> to login.";
}

}
}
else //this will show the form if not registered.
{

?>

<form action='register.php' method='POST'>
Choose username:<br />
<input type='text' name='username'><p />
Choose password:<br />
<input type='password' name='password'><p />
<input type='submit' name='register' value='Register'>
</form>

<?php
// Leave this here, I know it looks like its a random piece of code, but if you look above, you'll
see else {, this is to END that. Or else errors would occur, and the form would always show.
}

?>


Right, so on this page, the user can register. It checks if the username is already taken, md5's the password for extra security, and more. Read the comments throughout the script to understand.

The login page

Make a new file. Call it login.php and paste the following code.

Code:
<?php
include 'connection.php';

$session_username = $_SESSION['username'];

if ($_POST['login'])
{
//this is to get the form data
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);

// To protect from MySQL injection.
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

// make sure user put in all fields
if (!$username||!$password)
echo "Couldn't login, please enter a username and password";
else
{
//to log in
$login = mysql_query("SELECT * FROM users WHERE username='$username'");
if (mysql_num_rows($login)==0)
echo "No such user";
else
{
while ($login_row = mysql_fetch_assoc($login))
{

//get the database password
$password_db = $login_row['password'];

//encrypt the password in the form
$password = md5($password);

//check password
if ($password!=$password_db)
echo "Incorrect password";

else
{
$_SESSION['username']=$username; //give session
header("Location: login.php"); //refresh the page after form submitted

}
}


}
}

}
else
{

if (isset($session_username))
{
echo "You are logged in, $session_username. <a href='logout.php'>Log out</a>";
//basically, login was successful, they get this message. Additionally, user is already logged in, so
form will not show.
}
else
{
echo "
<form action='login.php' method='POST'>
Username:

<input type='text' name='username'><p />
Password:

<input type='password' name='password'><p />
<input type='submit' name='login' value='Log in'>
</form>
";
}
}
?>


So, obviously, this allows the user to login. The user is assigned a session, and if the username exists, and the password entered matches the one in the database, you'll be successfully logged in. Also, notice there's a part in the code that says protect from MySQL injection, leave that in, as it is VERY important.
MySQL injection, is when some hacker puts in a code into the login part, and lets them login, while adding or removing lines in the code.
For more information on it, I suggest you google it. Now, read the comments in the script, and you'll understand more

The logout page

Code:
<?php
session_start(); //Start the session
session_destroy(); //Destroy the session.
echo "You have been successfully logged out.<br>"; // This sentence and the one on the bottom are optional (you can also edit them, obviously) , you can take them out if you'd like, but I suggest you leave them to let the user know they have successfully logged out.
echo "If you would like to login again, <a href='login.php'>Click Here!</a> If not, return <a href='index.php'>Home</a> ";
?>


This is simple enough, it just destroys the session, and echo's if it was successful, and to login again, or return home.
Edit as you like, and read the comments in the script to understand more.

ALRIGHT! So that's the script! It's basically a very simple login script, and it's up to you on how to use it on your website.
In the future, I plan on adding another script with added features, like admin, permissions, PM's..etc. If you need any help, use the comment form below to ask me something.
Thanks for reading, and I hope you enjoy this!

  Mxx Digg StumbleUpon  

| Written by: Icy | Added: Nov 7 2009 | Last Modified: Dec 21 2009 | Views: 1,075 | (Log in to rate) |

Member Comments

Page: << Previous - 1 2  
IC Staff

Site: icecaves.net
Gender: Male
Karma: +1
*nod* What Thomas said. *nod*.XD   
Glitch Reporter

Site: icecaves.net
Age: 13
Gender: Male
Karma: +3
You must have been in a hurry. There's was over 15 typos. I'm gonna read through it again and if everything is fine I'll edit it and fix the typos.


  
IC Staff

Site: icecaves.net
Gender: Male
Karma: +1
15?! :O
Woah. xD
I think Kyra needs to shape us into little mini grammar ninja's xD!   
Glitch Reporter

Site: icecaves.net
Age: 13
Gender: Male
Karma: +3
I just fixed all the typos and stuff. x)

Solo said:
Wow! Well done Icy
As you are nearly as genius as Haily, could you make a PHP/MySQL news and comments thing. That would be really useful, as cutenews is really annoying me.
  *moonwalk*


I have a News and Comments script. I just need to add a Category feature. Maybe I can put in on IC once that's done.


  

Site: hiddenstar.c...
Age: 13
Gender: Male
Karma: 0
Nice tutorial, this looks like it will be useful. (:   

Site: t-n-f.co.nr
Gender: Female
Karma: 0
Hey Thomas, I think you should try out FanUpdate! hehe

this script is useful though I already used my mySQL on this account ;(   
Bazinga!

Age: 15
Gender: Female
Karma: 0
aashnisgraphics said:
Hey Thomas, I think you should try out FanUpdate! hehe

Thomas has something against fanupdate/wordpress...actually, pretty much every CMS out there XD


"I'm not insane, my mother had me tested!"

Site: t-n-f.co.nr
Gender: Female
Karma: 0
kyra said:
aashnisgraphics said:
Hey Thomas, I think you should try out FanUpdate! hehe

Thomas has something against fanupdate/wordpress...actually, pretty much every CMS out there XD


Haha... Well, you're amazing at coding, so I think you'll be fine without them

and these codes just don't wanna work for me I tried them out.. epic fail!   

Page: << Previous - 1 2  

In order to post a comment, you must be logged into the IceCaves.net Community.
Click here to login.


SkylishStarlett
The IceCaves.net Topsites


| Smiley Helper | FGN-Guild.com | Gamexe.net | Tugboat | Paint-Pops.net | Guildpets | Neo Nutters | RainbowBliss | Vintaged.org | NEOHEADS | Neo-Richies | Soo-Sweet | Darkgirl's Life | Figmint | Animal Palace | The New Fearless | Neo Crave | Moo Lovett |