how to create make a secure php login script with database password verification mysql

Mobile
feeds
Welcome Login | Register

how to create make a secure php login script with database password verification mysql
Reply Your Comments:
Click this button if you are interested in replying to this topic and leave your comments
Sent To Friend
CLick this button if you want to send this page to a friend.
Subsribe To Rss Feeds
Subscribe to RSS
CLick this button if you want to subscribe to this RSS Feed. You can use your browsers feeds burners if you have mozilla or internet explorer 7 or higher and keep up with updates.
  Forums Index
      » PHP Forums
        » » how to create make a secure php login script with database password verification mysql
how to create make a secure php login script with database password verification mysql
Post Description: how to create make a secure php login script with database password verification mysql PHP
Post Tags:
This Post Has Been Viewed 8038 Times Since Sat May 26, 2007 10:40 am Author hostman with 14 replies
how to create make a secure php login script with database password verification mysql
Advertise On This Page




ok, if you have a website, sometimes its helpful to have a login script for you members.

if you have a php website, the folks at Webune.com Hosting have provided us with this script you can use on your pages.

step 1. create your mysql table:

CODE:
CREATE TABLE `members` (
`user_id` int(4) NOT NULL auto_increment,
`username` varchar(65) NOT NULL default '',
`password` varchar(65) NOT NULL default '',
PRIMARY KEY (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

--
-- Dumping data for table `members`
--

INSERT INTO `members` VALUES (2, 'admin', MD5('password');


make sure to change these two lines according to your database. you need to provide:
hostname
database user name
database user name password
database name

so make sure to edit these lines:
$db = mysql_connect("localhost", "user", "password");
mysql_select_db("thiscript",$db);


or else, the script will now work because it cannot connect to your database to validate that the user and password provided in the form is good or not and your script will fail and give you error.



CODE:
<?
# PLEASE DO NOT REMOVE THIS
# THIS SCRIPT WAS CREATED BY WEBUNE.COM
# FIND PHP HOSTING AT WWW.WEBUNE.COM
# FREE WALLPAPERS AND SCRIPTS AT WWW.WALLPAPERAMA.COM
session_start();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Simple Login Script Crated By Wallpapera and Webune Hosting</title>
</head>
<body>

<h1><img src="http://www.webune.com/images/logo4.jpg">~ Webune Login Script ~</h1><hr>
<?
function form($error)
{
?>
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">

<tr>
<form name="form1" method="post" action="">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">

<tr align="center">
<td colspan="3"><? if($error){ echo $error; } else { echo '<strong>Member Login </strong>'; } ?></td>
</tr>
<tr>
<td width="78">Username</td>

<td width="6">:</td>
<td width="294"><input name="username" type="text" id="username"></td>

</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="password" type="password" id="password"></td>

</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td><input type="submit" name="Submit" value="Login"></td>

</tr>
</table>
</td>
</form>
</tr>
</table>
<?
}
function login_check($username,$password)
{

$db = mysql_connect("localhost", "user", "password") or die('Script Could not connect to database');
mysql_select_db("script",$db);

# THE WILL HELP YOU WITH SQL INJECTION
$password = mysql_real_escape_string(md5($password));
$password = mysql_real_escape_string($username);

$sql = "SELECT username,password FROM members where username = '".$username."'";

$result = mysql_query($sql ,$db);
if ($myrow = mysql_fetch_array($result))
{
if($username == $myrow['username'] && $password == $myrow['password'])
{
$login_check = true;
}

else
{
$login_check = false;
}
}
else
{
$login_check = false;
}

return $login_check;
}
if(isset($_REQUEST['Submit']))
{
if(!$_POST['username'] || !$_POST['password'])
{
$error = 'Error: All fields are required';
echo form($error);
}

else
{
if (login_check($_POST['username'],$_POST['password']))
{
echo 'Congratulations! You are now logged in<br><a href="./">Continue</a>';

session_register("username");
session_register("password");
}
else
{
$error = "Invalid username or password, try again";

echo form($error);
}
}
}
else
{
if($_GET['logout'])
{
session_destroy();
$error = "Logged Out Success - Try Again"; echo form($error); } else { if ($_SESSION['username']) { if (login_check($_SESSION['username'],$_SESSION['password'])) { echo '<a href="?logout=yes">Log out</a>Wallpaperama is a collection of high quality, high resolution wallpapers for free. Download Free Wallpapers for free at Wallpaperama.com'; } else { $error = "Please Login"; echo form($error); } } else { $error = "Welcome, Please Login"; echo form($error); } } } ?><div align="center">
<p>&nbsp;</p>
<p>PHP Hosting By <a href="http://www.webune.com">Webune.com</a></p>
</div> </body>

</html>



you can copy and paste the code above in notepad if you like then save as login.php and upload to your php website.

IMPORTANT: This short tutorial is intended to teach you a little about how you can insert data into mysql using a username example. you shoule not implement this on a production/public website, there are other security issues you need to be concern of, like something called sql injection. also you must have php on your site: if you don't have PHP, you can buy a PHP plan at our friends at Webune.com

after you have uploaded login.php to your site, open it with your browser and you can login with the default username and password:

username: admin
password: password

hope this helps.

Thanks Webune.com for their support on this.



Leave Your Comments

Your Name
Your Email Address (Will Not Be Published)
Notify Me When Someone Replies to this Page
(An email will be sent to you when someone replies to your comments)
Your Comments
Include A Picture with your comments
Share
| More
Share this page by putting this URL in your comments to other websites like myspace, Facebook, Twitter friendster, Hi5, Groups, Boards, Forum or others. Just Copy and Paste this Code
URL:
To embed this topic, just copy the code from the "Embed" box. Once you've copied the code, just paste it into your website or blog to embed it.
Embed:
BBCODE is use on forums. You can put this code on all your BBCODE enabled forums like PhpBB, vBulletin® and others. Just Copy and Paste this code on your Posts and Replies on your forums
BBCODE:
Subscribe Feeds
Webmasters - Exchange Links With Us. Add related websites to this topic
Add Link:
Links Related to : how to create make a secure php login script with database password verification mysql

Comments and replies About how to create make a secure php login script with database password verification mysql
:: 1 :: Reply #5109 Reply By yako On Fri Jun 01, 2007 3:53 pm
yako:
this is a login script i had saved in my notes but i dont remember where i got but it works great, very simple script:
create a file called: functions.php
<?php 
function createsessions($username,$password) 
{ 
    //Add additional member to Session array as per requirement 
    session_register(); 
    $_SESSION["gdusername"] = $username; 
    $_SESSION["gdpassword"] = md5($password); 
 
    if(isset($_POST['remme'])) 
    { 
        //Add additional member to cookie array as per requirement 
        setcookie("gdusername", $_SESSION['gdusername'], time()+60*60*24*100, "/"); 
        setcookie("gdpassword", $_SESSION['gdpassword'], time()+60*60*24*100, "/"); 
        return; 
    } 
} 
function clearsessionscookies() 
{ 
    unset($_SESSION['gdusername']); 
    unset($_SESSION['gdpassword']); 
 
    session_unset();     
    session_destroy(); 
    setcookie ("gdusername", "",time()-60*60*24*100, "/"); 
    setcookie ("gdpassword", "",time()-60*60*24*100, "/"); 
} 
function confirmUser($username,$password) 
{ 
    $md5pass = md5($password); 
    /* Validate from the database but as for now just demo username and password */ 
    if($username == "demo" && $password == "demo") 
        return true; 
    else 
        return false; 
} 
function checkLoggedin() 

 

Now Create a file called index.php
<?php 
ob_start(); 
session_start(); 
require_once ("functions.php"); 
if (checkLoggedin()) 
    echo "<H1>You are already logged in - <A href = \"login.php?do=logout\">logout</A></h1>"; 
else 
    echo "<H1>You are not logged in - <A href = \"login.php\">login</A></h1></h1>"; 
?>

 

Now save this file as login.php
<?php 
ob_start(); 
session_start(); 
require_once ("functions.php"); 
$returnurl = urlencode(isset($_GET["returnurl"])?$_GET["returnurl"]:""); 
if($returnurl == "") 
    $returnurl = urlencode(isset($_POST["returnurl"])?$_POST["returnurl"]:""); 
$do = isset($_GET["do"])?$_GET["do"]:""; 
$do = strtolower($do); 
switch($do) 
{ 
case "": 
    if (checkLoggedin()) 
    { 
        echo "<H1>You are already logged in - <A href = \"login.php?do=logout\">logout</A></h1>"; 
    } 
    else 
    { 
        ?> 
        <form NAME="login1" ACTION="login.php?do=login" METHOD="POST" ONSUBMIT="return aValidator();"> 
        <input TYPE="hidden" name="returnurl" value="<?$returnurl?>"> 
        <TABLE cellspacing="3"> 
        <TR> 
            <TD>Username:</TD> 
            <TD><input TYPE="TEXT" NAME="username"></TD> 
            <TD>Password:</TD> 
            <TD><input TYPE="PASSWORD" NAME="password"></TD> 
        </TR> 
        <TR> 
            <TD colspan="4" ALIGN="center"><input TYPE="CHECKBOX" NAME="remme">&nbsp;Remember me for the next time I visit</TD> 
        </TR> 
        <TR> 
            <TD ALIGN="CENTER" COLSPAN="4"><input TYPE="SUBMIT" name="submit" value="Login"></TD> 
        </TR> 
        </form> 
        </TABLE> 
    <? 
    } 
    break; 
case "login": 
    $username = isset($_POST["username"])?$_POST["username"]:""; 
    $password = isset($_POST["password"])?$_POST["password"]:""; 
    if ($username=="" or $password=="" ) 
    { 
        echo "<h1>Username or password is blank</h1>"; 
        clearsessionscookies(); 
        header("location: login.php?returnurl=$returnurl"); 
    } 
    else 
    { 
        if(confirmuser($username,$password)) 
        { 
            createsessions($username,$password); 
            if ($returnurl<>"") 
                header("location: $returnurl"); 
            else 
            { 
                header("Location: index.php"); 
            } 
        } 
        else 
        { 
            echo "<h1>Invalid Username and/Or password</h1>"; 
            clearsessionscookies(); 
            header("location: login.php?returnurl=$returnurl"); 
        } 
    } 
    break; 
case "logout": 
    clearsessionscookies(); 
    header("location: index.php"); 
    break; 
} 
?>

 

so now you should have three files, if you don't know how to save them, you can use notepad just copy and save them with notepad. then upload to your website which has PHP on it and that's it.

:: 2 :: Reply #47613 Reply By www.atokar.net On Sat Mar 29, 2008 3:31 am
www.atokar.net:
cool article!
:: 3 :: Reply #53304 Reply By bob On Sat May 10, 2008 1:41 pm
bob:
good job.but was looking for register to.
:: 4 :: Reply #58358 Reply By Nils On Thu Jun 19, 2008 12:35 am
Nils:
sorry. i was looking for a secure login. this code is vulnerable to something as simple as sql-injection.
:: 5 :: Reply #74051 Reply By Malinda On Sun Oct 05, 2008 12:08 pm
Malinda:
when i created the mysql database, it wouldn't let me use the md5('password'). it kept giving me an error until i took md5 off and just used a regular password. if i don't use the md5 does that mean that the rest of the script won't work? do you know how i can make the md5 password work?
:: 6 :: Reply #92267 Reply By ada On Sat Jan 31, 2009 7:21 pm
ada:
thank you, im starting to learn php, this helps me understand the concept. i searched everywhere but whenever i find a tutorial its meant for advanced programmers. its nice to find something for the biginner like me who is not an expert in php, this helped me get started.

thank you again sir
:: 7 :: Reply #95629 Reply By kiolpios On Sun Mar 01, 2009 8:10 pm
kiolpios:
i really need to create a quick mysql db with php secure login if you can send it to me please i can learn how to do this connection databases
:: 8 :: Reply #96127 Reply By Kenan On Fri Mar 06, 2009 7:12 am
Kenan:
oh man!
you make so much mistakes in your applications; you can not write php!
idiot!

god bless you.
:: 9 :: Reply #122054 Reply By sanjay On Tue Dec 01, 2009 3:25 am
sanjay:
i am in very trouble, because i don't know about php and php database. i am operating moneyinhands but i want user can register and login into my website with php and his database. i am very interested to know about php and his database, if you are good in php and his database please suggest and help me to i build better website for my users in india. if you want to charge any amount i will pay you just give me idea and support to i build website with login systems in php. i am waiting for you reply...
:: 10 :: Reply #128570 Reply By Sundar On Fri Feb 19, 2010 10:39 pm
Sundar:
this coding very helpfull for me...
I am confusing about how to create php login script...
thank you....
:: 11 :: Reply #128716 Reply By Marco On Mon Feb 22, 2010 4:45 pm
Marco:
This Code is a terrible mess.

MD5 values should be stored in a char(32) and don't need to be escaped. It just waste storage space and process time!

The code will also never work becouse:
[code=php]$pass = mysql_real_escape_string(
$password = mysql_real_escape_string( buggy and unusable code.
:: 12 :: Reply #128909 Reply By vandana On Thu Feb 25, 2010 5:47 pm
vandana:
tankx for this code.it will hepl me to create login page
:: 13 :: Reply #133499 Reply By Sam On Sun May 16, 2010 3:22 pm
Sam:
I think the title of this page is deceptive. This script is in no way secure. For those looking for security tips on login pages I have produced a small list off of the top of my head:

sammaye.wor
:: 14 :: Reply #136692 Reply By manas On Tue Jun 22, 2010 6:08 am
manas:
thank you very for your precious guidance. i was having problem since i am learning php through net , you make so easy