Making A Cool Login System With PHP, MySQL & jQuery

Making A Cool Login System With PHP, MySQL & jQuery

Introduction

Today we are making a cool & simple login / registration system. It will give you the ability to easily create a member-only area on your site and provide an easy registration process.

It is going to be PHP driven and store all the registrations into a MySQL database.

To add the needed flair, we are using the amazing sliding jQuery panel, developed by Web-kreation.

Step 1 – MySQL

First we have to create the table that will hold all the registrations. This code is available in table.sql.

table.sql

--
-- Table structure for table `tz_members`
--

CREATE TABLE `tz_members` (
  `id` int(11) NOT NULL auto_increment,
  `usr` varchar(32) collate utf8_unicode_ci NOT NULL default '',
  `pass` varchar(32) collate utf8_unicode_ci NOT NULL default '',
  `email` varchar(255) collate utf8_unicode_ci NOT NULL default '',
  `regIP` varchar(15) collate utf8_unicode_ci NOT NULL default '',
  `dt` datetime NOT NULL default '0000-00-00 00:00:00',
  PRIMARY KEY  (`id`),
  UNIQUE KEY `usr` (`usr`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Notice that we’ve defined the id as an integer with auto_increment – it is automatically assigned to every site member. Also, we’ve defined usr as an unique key – no two users with the same usernames are allowed.

We later use this in the registration to determine whether the username has been taken.

After you create the table, do not forget to fill in your database credentials in connect.php so you can run the demo on your own server.

Step 2 – XHTML

First, we have to incorporate Web-kreation’s form into our page.

demo.php

<!-- Panel -->
<div id="toppanel">

<div id="panel">
<div class="content clearfix">
<div class="left">
<h1>The Sliding jQuery Panel</h1>
<h2>A register/login solution</h2>
<p class="grey">You are free to use this login and registration system in you sites!</p>
<h2>A Big Thanks</h2>
<p class="grey">This tutorial was built on top of <a href="http://web-kreation.com/index.php/tutorials/nice-clean-sliding-login-panel-built-with-jquery" title="Go to site">Web-Kreation</a>'s amazing sliding panel.</p>
</div>

<?php
if(!$_SESSION['id']):
// If you are not logged in
?>

<div class="left">
<!-- Login Form -->
<form class="clearfix" action="" method="post">
<h1>Member Login</h1>

<?php
if($_SESSION['msg']['login-err'])
{
	echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
	unset($_SESSION['msg']['login-err']);
	// This will output login errors, if any
}
?>

<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="password">Password:</label>
<input class="field" type="password" name="password" id="password" size="23" />
<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> &nbsp;Remember me</label>
<div class="clear"></div>
<input type="submit" name="submit" value="Login" class="bt_login" />
</form>

</div>

<div class="left right">

<!-- Register Form -->

<form action="" method="post">
<h1>Not a member yet? Sign Up!</h1>

<?php

if($_SESSION['msg']['reg-err'])
{
	echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
	unset($_SESSION['msg']['reg-err']);
	// This will output the registration errors, if any
}

if($_SESSION['msg']['reg-success'])
{
	echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
	unset($_SESSION['msg']['reg-success']);
	// This will output the registration success message
}

?>

<label class="grey" for="username">Username:</label>
<input class="field" type="text" name="username" id="username" value="" size="23" />
<label class="grey" for="email">Email:</label>
<input class="field" type="text" name="email" id="email" size="23" />
<label>A password will be e-mailed to you.</label>
<input type="submit" name="submit" value="Register" class="bt_register" />
</form>

</div>

<?php
else:
// If you are logged in
?>

<div class="left">
<h1>Members panel</h1>
<p>You can put member-only data here</p>
<a href="registered.php">View a special member page</a>
<p>- or -</p>
<a href="?logoff">Log off</a>
</div>
<div class="left right">
</div>

<?php
endif;
// Closing the IF-ELSE construct
?>

</div>
</div> <!-- /login -->

<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left">&nbsp;</li>
<li>Hello <?php echo $_SESSION['usr'] ? $_SESSION['usr'] : 'Guest';?>!</li>
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>
<a id="close" style="display: none;" class="close" href="#">Close Panel</a>
</li>
<li class="right">&nbsp;</li>
</ul>

</div> <!-- / top -->
</div> <!--panel -->

At several places in this code, there are some PHP operators that check whether $_SESSION['usr'] or $_SESSION['id'] are defined. This is true only if the page visitor is logged in the site, which allows us to show specific content to site members. We will cover it in detail in a moment.

After the form, we put the rest of the page.

<div class="pageContent">

<div id="main">

<div class="container">
<h1>A Cool Login System</h1>
<h2>Easy registration management with PHP &amp; jQuery</h2>
</div>

<div class="container">
<p>This is a ...</p>
<div class="clear"></div>

</div>

</div>

Nothing special here. Lets continue with the PHP backend.

The login system

The login system

Step 3 – PHP

It is time to convert the form into a complete registration and login system. To achieve it, we will need more than the usual amount of PHP. I’ll divide the code into two parts.

If you plan to add more code, it would be a good idea to split it into several files which are included when needed. This aids the development of large projects and allows code reuse in different parts of a site.

But lets see how we’ve done it here.

demo.php

define('INCLUDE_CHECK',true);

require 'connect.php';
require 'functions.php';

// Those two files can be included only if INCLUDE_CHECK is defined

session_name('tzLogin');
// Starting the session

session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks

session_start();

if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe'])
{
	// If you are logged in, but you don't have the tzRemember cookie (browser restart)
	// and you have not checked the rememberMe checkbox:

	$_SESSION = array();
	session_destroy();

	// Destroy the session
}

if(isset($_GET['logoff']))
{
	$_SESSION = array();
	session_destroy();
	header("Location: demo.php");
	exit;
}

if($_POST['submit']=='Login')
{
	// Checking whether the Login form has been submitted

	$err = array();
	// Will hold our errors

	if(!$_POST['username'] || !$_POST['password'])
		$err[] = 'All the fields must be filled in!';

	if(!count($err))
	{
		$_POST['username'] = mysql_real_escape_string($_POST['username']);
		$_POST['password'] = mysql_real_escape_string($_POST['password']);
		$_POST['rememberMe'] = (int)$_POST['rememberMe'];

		// Escaping all input data

		$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));

		if($row['usr'])
		{
			// If everything is OK login

			$_SESSION['usr']=$row['usr'];
			$_SESSION['id'] = $row['id'];
			$_SESSION['rememberMe'] = $_POST['rememberMe'];

			// Store some data in the session

			setcookie('tzRemember',$_POST['rememberMe']);
			// We create the tzRemember cookie
		}
		else $err[]='Wrong username and/or password!';
	}

	if($err)
		$_SESSION['msg']['login-err'] = implode('<br />',$err);
		// Save the error messages in the session

	header("Location: demo.php");
	exit;
}

Here the tzRemember cookie acts as a control whether we should log-off users that have not marked the “remember me” checkbox. If the cookie is not present (due to browser restart) and the visitor has not checked the remember me option, we destroy the session.

The session itself is kept alive for two weeks (as set by session_set_cookie_params).

Lets see the second part of demo.php.

else if($_POST['submit']=='Register')
{
	// If the Register form has been submitted
	$err = array();

	if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
	{
		$err[]='Your username must be between 3 and 32 characters!';
	}

	if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
	{
		$err[]='Your username contains invalid characters!';
	}

	if(!checkEmail($_POST['email']))
	{
		$err[]='Your email is not valid!';
	}

	if(!count($err))
	{
		// If there are no errors
		$pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
		// Generate a random password

		$_POST['email'] = mysql_real_escape_string($_POST['email']);
		$_POST['username'] = mysql_real_escape_string($_POST['username']);
		// Escape the input data

		mysql_query("	INSERT INTO tz_members(usr,pass,email,regIP,dt)
					VALUES(
					'".$_POST['username']."',
					'".md5($pass)."',
					'".$_POST['email']."',
					'".$_SERVER['REMOTE_ADDR']."',
					NOW()
		)");

		if(mysql_affected_rows($link)==1)
		{
			send_mail(	'demo-test@tutorialzine.com',
					$_POST['email'],
					'Registration System Demo - Your New Password',
					'Your password is: '.$pass);
					$_SESSION['msg']['reg-success']='We sent you an email with your new password!';
		}
		else $err[]='This username is already taken!';
	}

	if(count($err))
	{
		$_SESSION['msg']['reg-err'] = implode('<br />',$err);
	}

	header("Location: demo.php");
	exit;
}

$script = '';
if($_SESSION['msg'])
{
	// The script below shows the sliding panel on page load
	$script = '
	<script type="text/javascript">
	$(function(){
		$("div#panel").show();
		$("#toggle a").toggle();
	});
	</script>';
}

We store all the encountered errors in an $err array, which is later assigned to a $_SESSION variable. This allows it to be accessible after a browser redirect.

You may have noticed on some sites, that when you submit a form and later refresh the page, the data is sent all over again. This could become problematic as it could lead to a double registrations and unnecessary server load.

We use the header function to prevent this, by redirecting the browser to the same page. This starts a fresh view of the page, without the browser associating it with a form submit. The result is that, on page refresh, no data is sent.

But as we use $_SESSION to store all the encountered errors it is important that we unset these variables, once we show the errors to the user. Otherwise they will be shown on every page view (the highlighted lines on the XHTML part of the tutorial).

Also notice how we create an additional script (lines 60-70 of the second part of the PHP code) which shows the panel on page load, so that the messages are visible to the user.

Now lets take a look at the CSS.

The registration / login system

The registration / login system

Step 4 – CSS

The sliding panel comes with its own style sheet. This means we are only left with creating the page styles.

demo.css

body,h1,h2,h3,p,quote,small,form,input,ul,li,ol,label{
	/* The reset rules */
	margin:0px;
	padding:0px;
}

body{
	color:#555555;
	font-size:13px;
	background: #eeeeee;
	font-family:Arial, Helvetica, sans-serif;
	width: 100%;
}

h1{
	font-size:28px;
	font-weight:bold;
	font-family:"Trebuchet MS",Arial, Helvetica, sans-serif;
	letter-spacing:1px;
}

h2{
	font-family:"Arial Narrow",Arial,Helvetica,sans-serif;
	font-size:10px;
	font-weight:normal;
	letter-spacing:1px;
	padding-left:2px;
	text-transform:uppercase;
	white-space:nowrap;
	margin-top:4px;
	color:#888888;
}

#main p{
	padding-bottom:8px;
}

.clear{
	clear:both;
}

#main{
	width:800px;
	/* Centering it in the middle of the page */
	margin:60px auto;
}

.container{
	margin-top:20px;

	background:#FFFFFF;
	border:1px solid #E0E0E0;
	padding:15px;

	/* Rounded corners */
	-moz-border-radius:20px;
	-khtml-border-radius: 20px;
	-webkit-border-radius: 20px;
	border-radius:20px;
}

.err{
	color:red;
}

.success{
	color:#00CC00;
}

a, a:visited {
	color:#00BBFF;
	text-decoration:none;
	outline:none;
}

a:hover{
	text-decoration:underline;
}

.tutorial-info{
	text-align:center;
	padding:10px;
}

Step 5 – jQuery

The sliding panel comes with its own jQuery files.

demo.php

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<!-- PNG FIX for IE6 -->
<!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 -->
<!--[if lte IE 6]>
<script type="text/javascript" src="login_panel/js/pngfix/supersleight-min.js"></script>
<![endif]-->

<script src="login_panel/js/slide.js" type="text/javascript"></script>

<?php echo $script; ?>

First we include the jQuery library from Google’s CDN. Later comes a special fix for IE6 PNG transparency issues and lastly the panel’s script is included.

At the bottom of the page is the $script variable – it shows the panel on page load if needed.

With this our cool login system is complete!

Conclusion

Today we learned how to use a fantastic form component and turn it into a functional log in / registration system.

You are free to built upon this code and modify it any way you see fit.

Join our newsletter and get our PSDs!19,448 people learn about HTML5, JS and more. Join them!

by Martin Angelov

Martin is a web developer with an eye for design from Bulgaria. He founded Tutorialzine in 2009 and it still is his favorite side project.

122 Comments

  1. Nokadota says:

    I had Web-Kreation's slide panel from awhile back but I was definitely missing this!

    I sure am glad I subscribed to this site, there are so many quality tutorials that I actually use. =)

  2. Michael says:

    I'm using this same thing on http://www.hokietextbooks.com/ It's quite a useful log-in system. Mine works on AJAX, but it's typically the same thing. Thanks for the post!

  3. MoneyQuick says:

    Nice tutorial ! Very cool looking and functional.

  4. Dave says:

    Thanks! Very pleasing to the eye. Tutorial is well-done!

    Dave

  5. Mantas says:

    Thats a nice tutorial, i will try to follow it and maybe make my own version of it, if i do i will post a link here, bookmarked!

  6. And_k says:

    Awesome tutorial man!! Your posts are very helpfull

    I just don't understand why you use rounded corners in CSS once they aren't suported by other browsers.

    P.S.: Sorry for the bad english, i'm brazilian

  7. Philipp says:

    Wow, this is incredible! thanx for that. Since years i use a php login script from evolt - know i change....

  8. Martin says:

    Thanks for the great comments!

    @ And_k

    An all-browser rounded-corner solution would cost too much in terms of development time for a feature that is not that important.

    Currently, three of the major browsers support rounded corners - Chrome, Safari and Firefox, which accounts for nearly a half of all web surfers. Other browsers will add this functionality soon.

    As rounded corners are not a crucial part of the functionality they can safely be left out for browsers that don't support them yet - also called graceful degradation.

  9. Dan P says:

    Thanks, Martin! Actually This is exactly the step I was pondering about in a development phase of the website. I was just going to use a wordpress system, but in the end I'd have to do way too much changing of the wordpress php login file, and the other admin php files, which would be annoyingly overwritten with each upgrade.

    So I may actually be using this, or more likely a modified version of the same idea.

    Oh, and since you added the -khtml border radius, then its 4 browsers, adding Konqueror, though its popularity is not very big compared to Firefox, so three MAJOR browsers, yeah, and a lot of the other browsers with small followings are usually based on the webkit engine, so its a lot of people! Just not IE.

    To be honest I still hate IE versions after 6. 6 is a horrible blunder, but 7 and 8 are still annoyingly behind in everything compared to basically every other browser.

  10. matt says:

    No no no!!! You never never ever store passwords as plain text in a database, how could you even begin to write this article without encoding passwords before storing them. I can't believe how irresponsible this article is.

  11. Martin says:

    @ matt

    I am encrypting the passwords with MD5 before storing them in the db (line 34 of the second part of demo.php in the PHP section / Step 3 of the article).

    You are right that passwords should never be stored as plain text, but here this issue is handled correctly and the system is secure and ready for use.

  12. matt says:

    looking at that line in your code, you are indeed md5-ing the password before storage, I could have sworn you were not when I posted my comment. If I missed that, my apologies.

    I would suggest you use a salt as well though:

    http://en.wikipedia.org/wiki/Salt_%28cryptography%29

  13. Arjun S Kumar says:

    Really a nice one..

  14. Monika says:

    i wish you would publish a really nice search engine ;)

  15. arnold says:

    you got lots of quality tutorials right here...might be useful in the future..

    I agree with Matt rounded corners is just for fancy design, nothing crucial

    anyway thanks for this!

  16. Human Bagel says:

    Nice tutorial, functional, nice and clean.

    I prefer to use a stronger hash than md5, though. I use Whirlpool or SHA512 a lot, but in the event of PHP 4, you can use the sha1() function, and as was said before, a salt always helps. ( http://humanbagel.com/blog/Proper+Hashing )

    Also, maybe I missed it, but why did you redefine the POST array? I have never tested this, but it might run faster with standard variables, unless I missed something.

    It wouldn't hurt to make `usr` and `pass` indexes to improve the speed of the database.

    Still, very nice tutorial, clean and functional!

  17. bhavesh says:

    Plz tell me how can I use your demo and download file on my blog.

    I want to add a "login" feature to my blog, that consists of an email address, password and a unique user ID. The feature should also be able to store the names, send an email verification reply, provide for emailing the user for forgotten passwords, etc.

    plz replay me on my mail address

  18. Martin says:

    @ Human Bagel

    Thanks for the comment! Your blog features some very interesting topics.

    A salt would be a nice addition to the system for those who need that bit of extra security.

    This tutorial was made to introduce the newbie developer to the process of developing a functional Log-in/Registration System and was kept low on security features. Of course, anyone is free to modify it and make it extra secure.

    Yes, you could use new variables to store the escaped $_POST data. This would also make the code a bit shorter.

    `usr` is already defined as a unique index - this ensures that the usernames are unique, and in the same time acts as a regular index.

  19. Roy says:

    Lovely Tutorial!

    I learning web design from http://www.w3schools.com/ and its hard to pick up by myself. I will try to follow the code and implement it onto my learning webpage.

    Just one question:

    setcookie('tzRemember',$_POST['rememberMe']);

    So it sets the cookie "txRemember=1"? And I've learnt that session data is lost every time the browser is restart, so I couldn't understand how it remembers me even after i restart the browser, as i couldnt find in the code how it stored the username and password as a cookie.

    Thanks, Roy.

  20. Lost like will ferrel says:

    Hello,
    This is an excellent tutorial and i want to thank you for makin it so easy for all of us. I am a seasoned beginner with php and mysql, i got all of this to work except the most important part.......registration, after i went through the tutorial i tried starting over clean and just uploading the source files directly to see if it would work...i still am having the same issues as before i keep getting "This username is already taken"...but, it is the only database i have up and it is the first time i am trying to register...the user i have set up has full permissions to the database so i am confused...any thoughts?

  21. Lost like will ferrel says:

    nevermind...everything is fine, I misspelled the name of my database in the connect file...lol, thanks again! Great tutorials, you have an excellent site.

  22. Wow this is a nice login script, may have to use this one on my next website.

    Consider it bookmarked :)

    Thanks

  23. Sweet tutorial says:

    Are you going to eventually transform this into a full on member access tutorial? Like showing how to add a password reset?

  24. Alex says:

    I can't get this to work on my server. I use msmtp for mail - "sendmail" is an alias for msmtp on my system.

    In any event, something odd happens when I click on "register": I am told that I have been registered, yet, no email gets sent. I have checked my "mail()" functionality in a standalone PHP file, and it works fine from the command line. I have a couple of MediaWIki installations that have no problems sending mail, but this one just doesn't seem to send.

    Is there something I'm doing wrong? I have tested this on Safari 4.0.3 on a Mac and Firefox 3 on Ubuntu 9.04 - same result.

  25. Jacques says:

    Hey there Martin!

    This Login System is perfect for what I need. I did everything as was required. The database and everything is set up and works.

    The thing is when I run it on my test server and attempt to register (a test run) it, I keep on receiving the message:
    "This username is already taken!"

    The funny thing is the database is still empty!

    Am I missing something. Do I need additional files or script in order for this to work or is everything I need there, but just have it wrong?

    any advice? please help (:

  26. Jacques says:

    Uhm... P.s. I didn't misspell my database name.... ?

  27. Jacques says:

    Still stuck with the previous thing, while I wrap my mind around that, here is another question:

    Since I am adding a Login System I obviously need my login page to be php and not html, the question is, can I keep the rest of my pages html and simply add in a log off link or do i need to make them all php?

  28. Martin says:

    @ Alex

    You can try and modify the code to use the mail() function directly - you'll only need to copy the code inside the send_mail() function I've made and paste it directly in demo.php (line 42 in the second part of the file in the PHP section of the tutorial).

    @ Jacques

    You do not need any additional scripts to run the demo. Just make sure your database and log in information is correct (maybe try to log in via PHPAdmin to make sure they are correct).

    For the second part of your question: Your pages can be HTML and you can provide a log-out link. However, if you'd like to limit certain pages only to registered uses (like registered.php in the demo), you'd have to make them PHP (by checking whether $_SESSION['id'] exists you can decide if the user is a logged in member or not and take appropriate actions).

  29. Jacques says:

    Martin

    Okay. I loged into PHPAdmin and checked. They seem to be in order, however I did see that that my database Collation was set to: "latin1_swedish_ci" I am not too sure if that is my problem but I changed that Collation to: "utf8_general_ci" and will let you know if it helped.

    Then if I go into PHPAdmin it gave me all kind of weird and wonderful information, but I saw it also indicate the Tables you have. One can go and set tables manually, but since the file: "table.sql" create the tables as needed, I left those alone.

    The thing I am trying to understand is that the code determin what happens next in terms of the user actions, but I cant seem to see where "table.sql" fits in or where the script tells it to create a new table.

    So I was wondering if that might be where my problem is, maybe I messed the script file somewhere and now it doesn't create a new tables in my database and thus give me the: “This username is already taken!”

    Can you advise me on this?

    Many thanks!

  30. Jacques says:

    Martin.

    The other thing I am looking at is how my users can obtain lost/forgotten
    passwords which must obviously be obtained through another piece of script.

    I have some script options with me, but was wondering if you could give us a tutorial on how to implement such script with this Login System?

    Give you lots of work, sorry!
    will add you to my Christmas list. lol.

  31. Jacques says:

    Martin

    Still stuck, nothing seems to be working here. not sure where my mistake is.

    When I create a MySQL database does it matter what I name this database or can I name it anything as long the "table.sql" info correspond with my database?

    Next thing:

    Do I have to go into PHPAdmin and set anything up there before this will work?

    Time: 15:18:28

  32. Jacques says:

    Martin

    Login System is now working!

    This is what I did:

    Firstly, all the files included in this demo is complete and very basic but one need to enter the correct details where required.

    Then one have to create an MySQL database (the name does not matter as long as your info correspond with connect.php)

    Upload and test!

    With the problem I had, Martin suggested I should ensure that the database and log in information is correct.

    I checked it and it was all in order!

    Martin also suggested to log in via PHPAdmin (this you can find on the Cpanel of your website).

    So I did. I noticed that my database exist but that there where no tables. (This may be different from web host to web host).

    I then copied all the info found in "table.sql" and pasted it into the area of my PHP Admin :" Run SQL query/queries on database yourdatabase_name" and executed the command.

    The info was then added and checked out ok.

    Went back to my test server and wouldn't you know, it worked!
    All is well, it sends emails with the password.

    Thank you for this great Tutorial Martin and for the resources and your help!

    I posted this in order for your other visitors to use this post for trouble shooting, should they encounter the same problem.

    Many thanks!

  33. Jacques says:

    Hey.

    Got stuck trying to get the "forget password feature" to work any help or scripts would be appreciated.

  34. Mia says:

    I love this drop down , I currently have it on my new site Im building , but I'm utilizing it as a contact form . Again , another awesome tut :)

  35. markus says:

    When i try to test it using wamp i get the following errors
    Any ideas ?

    Notice: Undefined index: id in C:\wamp\www\LoginDemo\index.php on line 19

    Notice: Undefined index: submit in C:\wamp\www\LoginDemo\index.php on line 40

    Notice: Undefined index: submit in C:\wamp\www\LoginDemo\index.php on line 83
    The Sliding jQuery Panel
    A register/login solution

  36. azeem says:

    Hi,
    The tutorial should have been more detailed. I am not able to understand a few points.

  37. Martin says:

    @ markus

    Your error level is set too strict and notices get reported as errors. The script will still work perfectly, though.

    You can probably change the error-reporting level from wamp's configuration, or you can add this line of PHP code on the top of demo.php (above define('INCLUDE_CHECK',true); ):

    error_reporting(E_ALL ^ E_NOTICE);

    @ azeem

    You can post your questions here and I will answer them.

  38. NeonDevil says:

    I had to add "margin:0;" to ".tab ul.login li" in "slide.css" - without it, my reset css would muck up the spacing in the tab.

    Hopefully this helps in case someone is integrating it into an existing site.

  39. markus says:

    Thanks for the quick response - that worked perfect

    by the way - awesome job with this tutorial and great site

  40. Janaka says:

    Wow...! This is a nice login script.

    Thanks.

  41. bklyn2cali says:

    how do i incorporate this script(s) into my webpage?

    where would i begin?

    thanks!
    -

  42. Alex says:

    Hi there!

    I've set up this nice user reg system, but I cannot get it work, everithing is ok till I want to register a user, it says that the e-mail was sent with the pass, but I receive no e-mail.... please help

  43. cmn1009 says:

    Amazing login script! I have one question. I am trying to include this in an header file. It doesn't seem to work when I do that. The session doesn't carry over and it won't let me do any logging in unless I am on the homepage. Any suggestions?

    THANKS!

  44. Hi, just farting around and tested it out :) looks great man, can you tell me how i can make pages not available to users that havnt registerd... someone might have the url and can just post it without loggin, could you please help me out :)

    Love this site ! defenitly bookmarkd

  45. Think i got it, the registerd page is the page i can copy and rename to suite my needs ???? correct :D ?

  46. Robbie says:

    Great tutorial!

    My only question/concern is how do I have the login/register panel link redirect the user to a login/register page assuming javascript is disabled?

    If javascript is disabled, this whole thing does not work correct?

    Thanks,
    Robbie

  47. nautilux says:

    it's amazing

    thanks

  48. Webdevcm says:

    I'm not good with scripting ... but after creating the database ...
    I changed the database connection string .. and I get the following ..

    Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/content/53/5072953/html/demo.php on line 55

    Warning: Cannot modify header information - headers already sent by (output started at /home/content/53/5072953/html/demo.php:55) in /home/content/53/5072953/html/demo.php on line 77

  49. Robbie says:

    Can anybody also explain how to include forget password mechanism or password reset feature?

  50. dan says:

    how do i make a page not visable for non members?

    thanks allot.

  51. dani says:

    kk got it, you cant be botherd to tell me, i have tryd to ask you 4 times now, you seem to just delete my comment, on step 3 you say we will look at this closer but you never get back to that point.. please help me out... !

  52. Martin says:

    @ Alex

    You have to make sure that you are running PHP 5 and that the mail() function works on your server.

    @ cmn1009

    If the session doesn't persists it may be due that you are not including the session_start() lines, or you already have a differnt session defined (maybe from a different script or your own site's session).

    @ Robbie

    This entire form works only if JS is enabled. You can either encourage visitors to turn on JS (like facebook does) or provide an additional non-js form somewhere in the page.

    Unfortunately a "Forgotten password" feature is a subject worthy of a tutorial of its own and cannot be easily explained in a comment.

    @ Webdevcm

    By the looks of this error, it looks like your MySQL credentials are not filled in correctly (or your db host / db name) are not correct.

    @ dani

    This question was already answered in a comment above. You can see it here.

  53. bklyn2cali says:

    @Martin: how do i use/incorporate the download package/scripts into my website?

    i'd like to utilize this login script for a webpage, but i don't even know where or how to start.

    any guidance or suggestions is greatly appreciated!

    thanks!
    -

  54. Joemar says:

    I got a problem there, when I already filled up all the required filled in textboxes in REGISTER AREA,and when I click the REGISTER BUTTON, nothing happend. It always has a syntax above that says "The Username is already taken". whatever username I put, It always generate "already taken" I always try to fix it but the problem is still there.

    SOMEBODY HELP ME PLEASE!

  55. cmn1009 says:

    Hello again Martin. I haven't figured out the reason for the session issue yet, but I am having another problem. When I log in, it doesn't do anything except for on the home page. Does it not work with a header file? (/includes/header.php)?

  56. Short Stack says:

    Having a problem... Just set up and upon entering FIRST user, getting message "This user is already taken!"

    There are 0 records in the table.

    Any ideas what could be causing this?

    Thanks.

  57. bklyn2cali says:

    can someone explain how would i use and incorporate the files in the demo.zip on my website? any help is greatly appreciated.

    thanks!
    -

  58. Garth says:

    Is there a way to launch the panel from another button somewhere else on the page?

  59. Lamoni says:

    Amazing tutorial! Thank you for this :]

  60. cky05 says:

    Hey,

    thx thats a great script but i've a problem with my database:

    #1064 - You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'collate utf8_unicode_ci NOT NULL default '',
    `pass` varchar(

  61. bklyn2cali says:

    hi there. is there a step-by-step guide/tutorial on how to actually use the files and scripts?

    i know extremely little (actually nothing) about mysql and php and would love to be able to use this script package for a site i'm trying to build.

    even if i were shown the steps needed (where to put the files, how to code the files into my index.html page), i think i could figure out the rest.

    help!! anyone?
    thanks!

  62. Carmen says:

    I've been looking for this for a long time! Great post!

  63. Michael Custer says:

    hmm...the idea is really great...
    but my problem is that it doesnt matter which name i fill into the new-members-part..it always says that this username is already taken...even if i fill in the weirdest names...

    sorry for my english but im from germany XD :D ;D

  64. beemol says:

    Hi,
    This script is great and works fine, thanks for it !!

  65. Rayhan says:

    How to add table.sql and integrated this to database?

  66. Rayhan says:

    I got error when try ad this to SMF forum.

    "Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/khadhafi/public_html/secure/forum/demo.php on line 58

    Warning: Cannot modify header information - headers already sent by (output started at /home/khadhafi/public_html/secure/forum/demo.php:58) in /home/khadhafi/public_html/secure/forum/demo.php on line 79"

    Can any one tell me whats the meaning of this error?

    Thanks

  67. Rayhan says:

    Still can't register as new member. Even i make new database in my cpanel. Its always say's :
    "This username is already taken!"
    Waiting for every one for the reply here, thanks!

  68. marvinstefani says:

    Your post is really appreciated
    Thank you for this Tutorial

    QUOTE|Unfortunately a “Forgotten password” feature is a subject worthy of a tutorial of its own and cannot be easily explained in a comment.|QUOTE

    Maybe you can add this here in the body-text since its pretty important that members can access even if they forget password, dont you think?

    Thanks anyway for this great idea

  69. Michael says:

    @Garth Having another button trigger it is pretty easy to do. Whatever button, etc. you put it on, add an onclick='$("div#panel").slideDown("slow"); '

    For example...
    My button

    You can put that on a link, or really anything. What might be best is to make a function that checks if it's already down, and then either do slideUp, or slideDown depending on what you need to do.

  70. aglan says:

    Thanks that's a really nice work

  71. sonichtmtl says:

    Very Cool.
    Thank you for shared.

  72. Morten says:

    Hello, i have completed the whole script now but i got two questions!
    1. How to i get the panel bar over to my own site at the top of http://dawnforged.com/indexforce.html ?

    2. How do i change the email who sends the password to one of my own?

    please help mate!

  73. regedit says:

    can anibody help me please?(((i received this errors:

    Notice: Undefined index: id in y:\home\login\www\index.php on line 18

    Notice: Undefined index: submit in y:\home\login\www\index.php on line 39

    Notice: Undefined index: submit in y:\home\login\www\index.php on line 82

    an when i put something in space for register when i click register i received this errors:

    Notice: Undefined index: id in y:\home\login\www\index.php on line 18

    Notice: Undefined index: username in y:\home\login\www\index.php on line 88

    Notice: Undefined index: username in y:\home\login\www\index.php on line 93

    Warning: Cannot modify header information - headers already sent by (output started at y:\home\login\www\index.php:18) in y:\home\login\www\index.php on line 143

  74. Aglan says:

    Hello,

    Thanks for this great tutorial, i had problem the panel floats behind my main menu check it here http://www.mydesk.us.com/demo2 this happens in firefox and safari , ie works fine.

    Thanks in advance

  75. Aglan says:

    hello again,

    found it in login_panel/css/slide.css icrease the number of z-index in top panel line z-index: 999999;

    Best Regards

  76. Blaise Kal says:

    It looks very cool, but why no live Javascript/Ajax form validation (next to server-side validation) and sending while you were at it?

  77. antisigma says:

    Fantastic tutorial! Easy to follow, well written and uses new technology.
    5 Stars!

    Keep up the good work!

  78. kerron says:

    Hi Martin,

    i'm not receiving any emails when i register. i read through the comments and someone was having a similar problem... you said they should be running php 5 and also try referencing it directly in demo.php. well i'm using php 5 so i dont think that's the problem. how would i go about referencing the send_mail directly into the demo.php file and where exactly? and if this doesn't work which other solutions would you suggest?

    also, can i change the 'demo-test@tutorialzine.com' to whatever i like? or must it remain as it is for the code to run properly.

    any help would be grateful.

  79. sergio_mx says:

    Ver good login div, this page have amazing tutorials.

    If someone want the panel to be always on the top position of the page just add 'position: fixed' in the #toppanel class. And make sure you delete the href="#" from the .

    #toppanel {
    position: absolute; /*Panel will overlap content */
    /*position: relative;*/ /*Panel will "push" the content down */
    top: 0;
    width: 100%;
    z-index: 999;
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    position: fixed;
    }

  80. Zrce Urlaub says:

    cool tutorial. i will bookmark this and use it next time when i need a login

  81. Dan says:

    I can't use this script. When I'm trying to login or register it doesnt work. I have even tried to take your sourcefiles and tried. I use PHP 5.3. I don't know what's wrong.

    Otherwise it's a nice tutorial.

  82. Dan says:

    When I'm trying to login or register it just refresh the page. Nothing else. I have only changed the design nothing with the php codes. I only changed ‘demo-test@tutorialzine.com’ to my own. Could that be the problem?

  83. Oscar says:

    After you create the table, do not forget to fill in your database credentials in connect.php so you can run the demo on your own server.

    Please tell me how to fill in my database credentials in connect.php? What line of that file are we talking about?

    Thanks ' )

  84. Rocktofakie3 says:

    When i try to register on this, it says username is already in use.

  85. Oscar says:

    Hey anyone knows how I can integrate this login system to an existing html web page?

    Thanks!

  86. Nat says:

    I have two questions...

    How could you make it so accounts could only be made on an approval-only basis?

    How can you let the user choose their own password?

    Sorry if these are stupid questions.

  87. Eli says:

    Well first it will be a PHP page ;)

    but from my experience you just download the source files and follow the template. If you study the code carefully you' catch on quick as to where you can put your existing HTML data and where to replace the code with your login script if need be.

  88. Ravi says:

    I got these errors when I try to log-in ...
    “Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/khadhafi/public_html/secure/forum/demo.php on line 58

    Warning: Cannot modify header information – headers already sent by (output started at /home/khadhafi/public_html/secure/forum/demo.php:58) in /home/khadhafi/public_html/secure/forum/demo.php on line 79″

    and I also got "this username is already taken" always whenever I try to register...

    Can any one tell me whats the meaning of this error?

    Thanks

  89. Nat says:

    @Ravi This happened to me and I found out I entered the wrong credentials/database for MySQL. Might want to check that.

  90. Oscar says:

    Hey It's fully working for me here is my website http://www.papaslive.com/cc

    THANK YOU!
    GREAT TUTORIALS.

  91. Isac says:

    OMG Jacques you are best and of course martin also :D but i did exactly as u had write about the sql and it work now also for meeeee :D:D:D

  92. Mefyu says:

    Hello. Very good and nice tutorial. Because i'm using this code, tutorial and it's very helpfull for me so I want to share with my sugestions about one better solution (i think so ;) )

    Because one of the comment was about disadvantage using JS in Login Form (because (i think) than people can not log on or register, when they have switch off JS) so i was modify a little part of code.

    In CSS:
    #toppanel {
    position: absolute; /* remove */
    position: relative; /* add */
    }
    #panel {
    display: none ;/* remove */
    display: block; /* add */
    }

    In JS i was add:
    $("#toppanel").css('position', 'absolute');
    $("#panel").css('display','none');

    After this modify, when peoples have JS switch off, than the div #panel is visible. When switch on, we have atributes from JS and we have sliding.
    ------------------------------------------------
    About: Undefined index ...
    I was trying add "isset" (for exaple if(!isset($_SESSION['idUser'])):) but then there are some problems with displaying error-messages, so as you said: adding
    error_reporting(E_ALL ^ E_NOTICE);
    is best resolution at this moment.
    ------------------------------------------------
    And now a little problem (as usualy with IE).
    On FireFox and Opera it's displaying OK but on IE (IE8) DIV #main isn't in the center only on right. This is my CSS: #main {width: 900px; margin: 50px auto;}. Have anybody some ideas?

    PS Sorry for my english ;)

  93. IT Portal says:

    Oscar thanks for posting your live example of this working on your site. I think overall a great tutorial

    josh

  94. Dharamveer says:

    This is the most awesome thing ever discovered by me online, great website i am fan, i love u guys

  95. Martyn says:

    Hey great tutorial really helpful, but I have a problem the login wont login, if i put a username and password into the manually database it for some odd reason doesnt read from the database and so wont log in, also how would I get it that when you log in it takes you to another page like index.php much appreciated thanks

  96. Jawad says:

    Thanks I've really wanted to understand this but now that I've found this I'll be reading it over the Easter holidays hopefully!!!

  97. Brenton says:

    Hey, this is a great tutorial, very helpful!

    Have you addressed the issue of the login tab image breaking apart when resizing the browser window very small.

    Big fan of the site, you guys have prime content!

  98. iMayne says:

    Im a noob so please see with me. Where do I change the default "admin/admin" username and psswd?

  99. alex says:

    Hi, i really need your help, i'm trying to develop a sistem like login/register, and i want users to update theyr profile so my BIG questions is
    i have this line SELECT id,usr,memb_level FROM tz_members WHERE and i don't know what to put there after the word WHERE.
    The page where the line is called edit_profile.php and some how i need to indentif the user i tryed to put dif php code but no results.
    Please help me!
    Warm regards,
    Alex
    Ps. nice tutorial

  100. awesome says:

    Hey,

    Thanks for this super cool code, however one problem, with IE7, top bar starts from the middle of the screen, any idea how to fix this issue?

    Firefox is all good.

    Any help would be appreciated.

    Cheers.

  101. @alex - is the user logged in on the page edit_profile.php? If so, then your SQL might be something like:

    $q = "SELECT id,usr,memb_level FROM tz_members WHERE id=".$_SESSION['userid'];

    This is presuming that when you logged the user in, you stored their user ID in that session variable.

    Otherwise, great script - have been looking for an unobtrusive login / registration box like this for a while. Cheers!

  102. Jacob Raccuia says:

    I figured out how to make the panel load opened.

    Removing this tag will do the trick

    if($_SESSION['msg'])
    at like line 61.

    Yeahhhhhhhh took me forever to figure it out!

  103. MacX says:

    Hellou, can you help me please...

    Warning: date() [function.date]: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected 'Europe/Berlin' for 'CEST/2.0/DST' instead in /Library/WebServer/Documents/pokus/functions.php on line 19

    Warning: Cannot modify header information - headers already sent by (output started at /Library/WebServer/Documents/pokus/functions.php:19) in /Library/WebServer/Documents/pokus/demo.php on line 143

  104. Al says:

    How to integrate this with vBulletin? ?

  105. Hi!, This article is opening my head and my website.

  106. Jason says:

    Awesome. Thanks for the great code.

  107. Al says:

    Hey Martin,
    maybe you can give us a micro tut on how to integrate this login system with vBulletin 4 ?

    I can give you access to a test vb4 installation if needed!

    Regards!

  108. Felix says:

    Hi, This script is fantastic. I am about to create a new website and will use it there.

    I changed it a bit here n there:

    - no username, login with email
    - forgotten password functionality

    Where can I donate?

    Thanks a lot for this. It just looks awesome.
    Felix

  109. Greg says:

    Love the script, thank you so much! I was wondering if you could help me with a question.... (or maybe Felix?)... you posted just what I need! How can I add login with email rather than username and the forgotten password function?

    Thanks again, great work!
    Greg
    (gregcaie@hotmail.com)

  110. Felix says:

    Hi Greg, send you an email.

  111. Wyatt says:

    Hi, super cool script, thank you!!!!!!!

  112. web designer says:

    Thanks Martin for sharing with us your tutorial, it's easy to understand, prety cool, and works so well.

  113. Wyatt says:

    Could someone help me out with a forget password script?
    It is really nice to have......

    thx.

    PS: Martin thanks again for this wonderfull thing

  114. Marc says:

    Brilliant tutorial, helped me a lot :)

  115. Hi..,

    This is a fantastic script, its very help to me..
    Good job you have been done.:-)
    Thanks a lot..!

  116. tAz says:

    This is a great script... that doesn't work out of the box... so it's a "project" not a "tutorial"...

    Not really a big problem for those with intermediate PHP skills but way out there for the new guys...

    Keep the tutorials coming please - but such large numbers of errors really distracts from the undoubted usefulness of this script.

  117. Matt says:

    ok I figured out where to find php errors. I looked through this page and am not sure if the problem was I had previously used a PHP script with Session Start. is there anything you need to get rid of the first session start other than running a destroy command? I removed the other script from my site.

    The error is (note I edited the path a little just for privacy):
    PHP Warning: session_start() [function.session-start]: open(/var/php_sessions/) failed: No such file or directory (2) in /hermes/bosweb/web256/b2562/demo/demo.php on line 16
    PHP Warning: Unknown: open(/var/php_sessions) failed: No such file or directory (2) in Unknown on line 0
    PHP Warning: Unknown: Failed to write session data (files). Please verify that the current setting of session.save_path is correct (/var/php_sessions) in Unknown on line 0

    Thanks for any help you can provide.

  118. Matt says:

    As you can tell I am learning. I found my issue in php.ini having to do with "session.save_path" once I defined that the script worked fully.

  119. Rohan says:

    FOR ALL GETTING WRONG USERNAME/PASSWORD Error

    Guys, there seems to be an issue with .md5 encryption used, remove that and it works all fine!!!

  120. Paul says:

    Hi All, I have a problem with cookies,
    Basically the script is working perfectly, but when I try to log off, I remain logged in unless I manually delete browser cookies.
    Looking at the php between lines 16 and 37, I think will give the answer. I haven't changed anything I don't think, but for some reason logging off isn't clearing the session.
    Any pointers would be much appreciated.

    Cheers

    Paul

  121. mikl says:

    I liked this code and I use it in manestate.com
    I am giving here the forgot/reset password script.
    I started from the code here http://www.phpeasystep.com/phptu/21.html and modified it. I hope it helps somebody.

    1. the html

    Enter your email :

    2. the form processing here

    <?php

    $host="localhost"; // Host name - update all those fields
    $username="root"; // Mysql username
    $password="*******"; // Mysql password
    $db_name="coollogin"; // Database name

    //Connect to server and select databse.
    mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
    mysql_select_db("$db_name")or die("cannot select DB");

    // value sent from form
    $email_to=$_POST['email_to'];
    // table name
    $tbl_name=tz_members;

    // retrieve password from table where e-mail is equal
    $sql="SELECT usr, pass, regIP FROM $tbl_name WHERE email='$email_to'";
    $result=mysql_query($sql);

    // if found this e-mail address, row must be 1 row
    // keep value in variable name "$count"
    $count=mysql_num_rows($result);

    // compare if $count =1 row
    if($count==1)
    {
    $rows=mysql_fetch_array($result);

    $your_username=$rows['usr'];
    $your_password=$rows['pass'];
    $your_ip=$rows['regIP'];
    $pass = substr(md5($your_ip.microtime().rand(1,100000)),0,6); // create a new pass
    mysql_query(" UPDATE tz_members SET pass='".md5($pass)."' WHERE email='".$email_to."'"); // update the db

    // ---------------- SEND MAIL FORM ----------------
    // send e-mail to ...
    $to=$email_to;

    // Your subject
    $subject="Your password here";

    // From
    $header="from: your name ";

    // Your message
    $messages= "Your password for login to manestate.com - My Properties has been reset.\r\n";
    $messages.="The new password is $pass \r\n";
    $messages.="Mikhael Lerman \r\n";

    // send email
    $sentmail = mail($to,$subject,$messages,$header);

    mysql_free_result($result);
    }

    // else if $count not equal 1
    else if ($count==0)
    echo "Your email was not found in our database";
    else
    echo "More than one (".$count.") email records was found in our database, please contact the administrator.";

    // if your email succesfully sent
    if($sentmail)
    {
    echo "The new password has been reset and sent to the email on record.";
    }
    else
    {
    echo "Cannot send the password to this e-mail address";
    }

    ?>

  122. Mikl says:

    Anyone can share a "change password page"? I need it for manestate.com. thx.

Comments are closed.