Here I will teach you how to create a really basic login-system for use in php and mysql. The system can easily be built on to work with flash and other applications.
I'll just start:
First you need a "data.php" file that looks like this:
<?php
$dbc = mysql_connect("localhost","***username***","***password***"); mysql_select_db("***db_name***");
session_start();
?>You also need a database with a table (registered) with fields that look like the SQL code below. (If you want, you can copy it into phpMyAdmin and it will create the table.)
CREATE TABLE `registered` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(64) NOT NULL,
`password` varchar(32) NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;Then (in the main file) we need to include the "data.php"-file:
<?php
include "data.php";
?><?php
function loginForm(){
?><form method="post">
<strong>Username:</strong> <input type="text" name="login[username]" /><br />
<strong>Password:</strong> <input type="password" name="login[password]" /><br />
<input type="submit" />
</form><?php
}
?>Now what this does, is that if we ever run the function loginForm() it will output all that HTML there (which of course just is a basic form).
Then we need to make a is_logged_in() function. The code for that should be:
<?php
function is_logged_in(){
//isset will return TRUE or FALSE
return isset($_SESSION['loggedIn']);
}
?>All this function does is to return whether or not the variable $_SESSION['loggedIn'] is set or not. If it is set - return true. If the session is NOT set - return false.
Now we need to make a function that tells us whether or not the user is trying to login.
<?php
function is_logging_in(){
return isset($_POST['login']);
}
?>This will return true if the post-variable login is set (remember, we put the input field inside an array named login... name="login[username]").
Now we need a function to do the login...
<?php
function login($username, $md5password){
$query = 'SELECT * FROM `registered` WHERE `username` = \''.mysql_real_escape_string($username). '\' AND password = \''. mysql_real_escape_string($md5password). '\'';
$rs = mysql_query($query);
if(!mysql_num_rows($rs)){
echo "<strong>Bad login!</strong><br />";
loginForm(); //here we ask the user to login again...
die();
}
while($row = mysql_fetch_assoc($rs)){
if($username == $row['username'] && $md5password == $row['password']){
$_SESSION['loggedIn'] = true;
die("<script language=\"javascript\">window.location.reload();</script>");
}
}
echo "<strong>Bad login!</strong><br />";
loginForm();
die();
}
?>Than we need a function to deal with what to do is to create a function to manage what to happen if the user is logged in:
<?php
function loggedIn(){
die("<h1>You are logged in!</h1>");
}
?>Ok... Now we just need to structure everything out...
<?php
if(is_logged_in()){
loggedIn();
} elseif(is_logging_in()){
login($_POST['login']['username'], md5($_POST['login']['password']));
} else {
loginForm();
}
?>All the code now looks like this:
<?php
include "data.php";
function loginForm(){
?><form method="post">
<strong>Username:</strong> <input type="text" name="login[username]" /><br />
<strong>Password:</strong> <input type="password" name="login[password]" /><br />
<input type="submit" />
</form><?php
}
function is_logged_in(){
return isset($_SESSION['loggedIn']);
}
function is_logging_in(){
return isset($_POST['login']);
}
function login($username, $md5password){
$query = 'SELECT * FROM `registered` WHERE `username` = \''.mysql_real_escape_string($username). '\' AND password = \''. mysql_real_escape_string($md5password). '\'';
$rs = mysql_query($query);
if(!mysql_num_rows($rs)){
echo "<strong>Bad login!</strong><br />";
loginForm(); //here we ask the user to login again...
die();
}
while($row = mysql_fetch_assoc($rs)){
if($username == $row['username'] && $md5password == $row['password']){
$_SESSION['loggedIn'] = true;
die("<script language=\"javascript\">window.location.reload();</script>");
}
}
echo "<strong>Bad login!</strong><br />";
loginForm();
die();
}
function loggedIn(){
die("<h1>You are loged in!</h1>");
}
//here komes the logic...
if(is_logged_in()){
loggedIn();
} elseif(is_logging_in()){
login($_POST['login']['username'], md5($_POST['login']['password']));
} else {
loginForm();
}
?>How would you make it goto another page?
nice tut
Just use session variables xD
if you use this script, your site will be vulnerable to sql injections via the username or password variable.
header() function can make it go into the main page
Nice Script, i got it to work, but how do people register into the database?
E-mail me a response, or let me know you replied...
This isn't a 100% bullet-proof script. It is just to show the basic idea of how these things work. Later on I will be posting my own extensive script that will be more suited to a live environment.
Here is a revision I did of this script:
<?php
//Include the database connection
include "data.php";
//In order to work with sessions we need use session_start()
session_start();
//Return true if the session is set
function is_logged_in(){
return isset($_SESSION['loggedIn']);
}
//Check to see if they posted a value called "login"
function is_logging_in(){
return isset($_POST['submit']);
}
//Function to show the login form
function loginForm(){
print '
<form method="post">
<strong>Username:</strong> <input type="text" name="username" /><br />
<strong>Password:</strong> <input type="password" name="password" /><br />
<input type="submit" name="submit" value="Login" />
</form>';
}
//See if the login matches a user in the database
function login($username, $password){
//Clean the values of XSS and Injections
$username = trim(htmlentities(strip_tags($username), ENT_QUOTES, 'UTF-8'));
$password = md5(trim(htmlentities(strip_tags($password), ENT_QUOTES, 'UTF-8')));
//Create the MySQL Query
$query = 'SELECT * FROM `registered` WHERE `username` = \''.mysql_real_escape_string($username). '\' AND password = \''. mysql_real_escape_string($password). '\'';
$result = mysql_query($query);
//If we found 1 or more users that matched the login
if(mysql_num_rows($result) > 0) {
$_SESSION['loggedIn'] = true;
header("Location: ". $_SERVER['PHP_SELF']);
exit;
} else {
echo '<strong>Bad login!</strong><br />';
loginForm(); //here we ask the user to login again...
exit;
}
}
//Print "You are loged in" and end the script
function loggedIn(){
die('<h1>You are loged in!</h1>');
}
//Here comes the logic...
//If they are already loged in
if(is_logged_in()){
loggedIn();
//Else if they have submited the form to login
} elseif(is_logging_in()){
login($_POST['username'], $_POST['password']);
//Else this must be the first time they have come so show the login page
} else {
loginForm();
}
?>You have a point there, unclean. The user and password variables need to be run through mysql_real_escape_string, and the header functions require the exit construct after them for if the browsers do not act on the location headers.
A nice login system article, although I would highly recommend the OOP approach to programming such systems. Perhaps that can come about in the next instalment :) ! Keep up the good work.
Adam @ TalkPHP.
I followed the intructions to a tee, and I have insert a username and a password in my table in the database, but it doesn't work. I try logging in with the correct username and password and it doesn't work! Could you tell me why it does this?
Try adding "print" statements after every statement. This is one way to see where in the script you are making it to. Then, if you see the WRONG print statement print you will know where to look. For example:
<?php
//If they are already loged in
if(is_logged_in()){
///////////////////////
print 'You are logged in';
loggedIn();
//Else if they have submited the form to login
} elseif(is_logging_in()){
///////////////////////
print 'You are logging in';
login($_POST['username'], $_POST['password']);
//Else this must be the first time they have come so show the login page
} else {
///////////////////////
print 'show the login form';
loginForm();
}
?>