Tuesday, August 5, 2014

1stwebdesigner

1stwebdesigner


How to Create a Login and Registration System Using PHP and MySQL

Posted: 05 Aug 2014 06:00 AM PDT

A secured login and registration system is a one of the important considerations when creating a system by scratch. One way to do that is by creating a registration system using PHP and MySQL.

Although there are a plenty of tutorials on the Web that teach how to create one using PHP and MySQL, most of them are for advanced learners.

This article is about how to write a simpler version of User Registration and Login System using PHP and MySQL for beginners. Let's get started!

Resources You Need to Complete This Tutorial

  • Xampp (PHP version 5.3 or later and MySQL version 4.1.3 or later)
  • Basic Knowledge about PHP, HTML and CSS
  • Time and Patience

What We Are Going to Build

screen

Download ZIP

Configuring Your Server

You can use any hosting service that has PHP and MySQL already installed (just make sure that it has the PHP version 5.3 or later and MySQL version 4.1.3 or later).

But for this tutorial, Xampp will be used as the server. If it's your first time installing Xampp, this article might help you how to install it properly on your computer.

Step 1 – MySQL

First,  create the database and table that will hold all the registrations. You can do this manually using the Graphical User Interface of PhpMyAdmin or use SQL to insert this information. Check out the SQL code below.

  /* Create Database */  CREATE DATABASE userlitdb;    /* Create Table */   CREATE TABLE `usertbl` (    `id` int(11) NOT NULL auto_increment,    `full_name` varchar(32) collate utf8_unicode_ci NOT NULL default '',     `email` varchar(32) collate utf8_unicode_ci NOT NULL default '',    `username` varchar(20) collate utf8_unicode_ci NOT NULL default '',    `password` varchar(32) collate utf8_unicode_ci NOT NULL default '',    PRIMARY KEY  (`id`),    UNIQUE KEY `username` (`username`)  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;    

Notice that all of them are varchar,  which even the password which will be converted later  to md5 character to secure the user’s password. Also, use an auto_increment to automatically assign an ID or a number to users who would register later.

Now that the table has been created, what you have to do the markup and the CSS first and then later the PHP.

Step 2 – The Markup

For the markup, this will include three files and all of them should be saved as ".php" file since you are doing a server-side scripting program.

First, create the login.php file. Go ahead and copy the codes below.

  <!DOCTYPE html>    <html lang="en">  <head>  	<meta charset="utf-8">    	<title>How to Create a Registration and Login System Using PHP and  	mySQL</title>  	<link href="css/style.css" media="screen" rel="stylesheet">  	<link href=      'http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800'  	rel='stylesheet' type='text/css'>  </head>    <body>  	<div class="container mlogin">      	<div id="login">          	<h1>LOGIN</h1>            	<form action="" id="loginform" method="post" name="loginform">              	<p><label for="user_login">Username<br>              	<input class="input" id="username" name="username" size="20"              	type="text" value=""></label></p>                	<p><label for="user_pass">Password<br>              	<input class="input" id="password" name="password" size="20"              	type="password" value=""></label></p>                	<p class="submit"><input class="button" name="login" type=              	"submit" value="Log In"></p>                	<p class="regtext">No account yet? <a href=                  "register.php">Register Here</a>!</p>          	</form>      	</div>  	</div>    	<footer>      	© 2014 <a href="http://www.1stwebdesigner.com/">1stwebdesigner</a>. All      	rights reserved.  	</footer>  </body>  </html>    

With this code, you'll have a similar result like the image below.

login

Next, create our register.php file. Copy and paste the code below.

  <!DOCTYPE html>  <html lang="en">  <head>  	<meta charset="utf-8">    	<title>How to Create a Registration and Login System Using PHP and  	mySQL</title>  	<link href="css/style.css" media="screen" rel="stylesheet">  	<link href=      'http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800'  	rel='stylesheet' type='text/css'>  </head>    <body>  	<div class="container mregister">      	<div id="login">          	<h1>REGISTER</h1>            	<form action="register.php" id="registerform" method="post" name=          	"registerform">              	<p><label for="user_login">Full Name<br>              	<input class="input" id="full_name" name="full_name" size="32"              	type="text" value=""></label></p>                	<p><label for="user_pass">Email<br>              	<input class="input" id="email" name="email" size="32" type=              	"email" value=""></label></p>                	<p><label for="user_pass">Username<br>              	<input class="input" id="username" name="username" size="20"              	type="text" value=""></label></p>                	<p><label for="user_pass">Password<br>              	<input class="input" id="password" name="password" size="32"              	type="password" value=""></label></p>       	         <p class="submit"><input class="button" id="register" name=              	"register" type="submit" value="Register"></p>                	<p class="regtext">Already have an account? <a href=              	"login.php">Login Here</a>!</p>    	      </form>      	</div>  	</div>    	<footer>      	© 2014 <a href="http://www.1stwebdesigner.com/">1stwebdesigner</a>. All      	rights reserved.  	</footer>  </body>  </html>  

Using the codes above, you'll have a similar result like the image below.

register

Next, create our intropage.php. This will serve as the main page once a user successfully logs in.

  <div id="welcome">              	<h2>Welcome, <span> USER </span></h2>!              	<p><a href="logout.php">Logout</a> Here!</p>  </div>  

With the codes above, you will get a similar result like the image below.
welcom

Step 3 – The CSS

Now that you have the markup ready, add the CSS. Basically, this will have the style for the class container of the pages as well as the buttons and some elements like text boxes and the likes.

  /*= GENERAL STYLES  --------------------------------------------------------*/  body {  	background: #efefef;  	font-family: 'Open Sans', sans-serif;  	color: #777;  }    a {  	color: #f58220;  	font-weight: 400;  }    span {  	font-weight: 300;  	color: #f58220;  }    .mlogin {  	margin: 170px auto 0;  }    .mregister {  	margin: 80px auto 0;  }    .error {  	margin: 40px auto 0;  	border: 1px solid #777;  	padding: 3px;  	color: #fff;  	text-align: center;  	width: 650px;  	background: #f58220;  }    .regtext {  	font-size: 13px;  	margin-top: 26px;  	color: #777;  }    /*= CONTAINERS  --------------------------------------------------------*/  .container {  	padding: 25px 16px 25px 10px;  	font-weight: 400;  	overflow: hidden;  	width: 350px;  	height: auto;  	background: #fff;  	-webkit-box-shadow: 0 1px 3px rgba(0,0,0,.13);  	-moz-box-shadow: 0 1px 3px rgba(0,0,0,.13);  	box-shadow: 0 1px 3px rgba(0,0,0,.13);  }    #welcome {  	width: 500px;  	padding: 30px;  	background: #fff;  	margin: 160px auto 0;  	-webkit-box-shadow: 0 1px 3px rgba(0,0,0,.13);  	-moz-box-shadow: 0 1px 3px rgba(0,0,0,.13);  	box-shadow: 0 1px 3px rgba(0,0,0,.13);  }    .container h1 {  	color: #777;  	text-align: center;  	font-weight: 300;  	border: 1px dashed #777;  	margin-top: 13px;  }    .container label {  	color: #777;  	font-size: 14px;  }    #login {  	width: 320px;  	margin: auto;  	padding-bottom: 15px;  }    .container form .input,.container input[type=text],.container input[type=password],.container input[type=e] {  	background: #fbfbfb;  	font-size: 24px;  	line-height: 1;  	width: 100%;  	padding: 3px;  	margin: 0 6px 5px 0;  	outline: none;  	border: 1px solid #d9d9d9;  }    .container form .input:focus {  	border: 1px solid #f58220;  	-webkit-box-shadow: 0 0 3px 0 rgba(245,130,32,0.75);  	-moz-box-shadow: 0 0 3px 0 rgba(245,130,32,0.75);  	box-shadow: 0 0 3px 0 rgba(245,130,32,0.75);  }    /*= BUTTONS  --------------------------------------------------------*/    .button{  border: solid 1px #da7c0c;              	background: #f78d1d;              	background: -webkit-gradient(linear, left top, left bottom, from(#faa51a), to(#f47a20));              	background: -moz-linear-gradient(top,  #faa51a,  #f47a20);              	filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#faa51a', endColorstr='#f47a20');              	color: #fff;  padding: 7px 12px;  -webkit-border-radius:4px;     -moz-border-radius:4px;      	border-radius:4px;  float: right;  cursor: pointer;  }    .button:hover{  background: #f47c20;              	background: -webkit-gradient(linear, left top, left bottom, from(#f88e11), to(#f06015));              	background: -moz-linear-gradient(top,  #f88e11,  #f06015);              	filter:  progid:DXImageTransform.Microsoft.gradient(startColorstr='#f88e11', endColorstr='#f06015');  }    /*= FOOTER  --------------------------------------------------------*/  footer {  	color: #777;  	font-size: 12px;  	text-align: center;  	margin-top: 20px;  }  

By this time, you'll have the same image like the final result above.

Step 4 – Re-using Elements

Now that you have all the markup and CSS ready, try to re-use elements like the head section and footer section. Inside your root folder, create a new folder and name it “includes“.

This will have all of the includes files. Next, create a new file inside the include folder name and it header.php. Copy the the head section part on any of the three php files you have created above. So you’ll have the code below.

  <!DOCTYPE html>  <html lang="en">    <head>              	   <meta charset="utf-8">     	<title>How to Create a Registration and Login System Using PHP and mySQL</title>    	<link href="css/style.css" media="screen" rel="stylesheet">              	            	<link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>    </head>                	<body>    

The next thing you need to do is remove the markup you copied on the header.php file on all the three php files you created and replace it with the PHP code below.

  <?php include("includes/header.php"); ?>  

Now, do the same thing with the footer. Copy the code below and create a new file name it footer.php. This will include the footer section. Copy the code below and paste it to footer.php file.

   <footer>© 2014 <a href="http://www.1stwebdesigner.com/">1stwebdesigner</a>. All rights reserved. </footer>  </body>  </html>  

Then, remove this part again to all of the three PHP files and change it to the following codes.

  <?php include("includes/footer.php"); ?>  

Step – 5 Connecting to Database

Now that you have included the files for the head section and footer sections, it is time to create a new include file. Name it constants.php and copy the code below.

  <?php  // Database Constants  define("DB_SERVER", "localhost");  define("DB_USER", "root");  define("DB_PASS", "");  define("DB_NAME", "userlistdb");  ?>  

In the code above, you created the constants of the database information so that you can easily change the information whenever you need to.

Next, create a new file on includes folder and name it connection.php. This will hold of the database connection codes. Go ahead and copy and paste the code below.

    <?php  require("constants.php");    $con = mysql_connect(DB_SERVER,DB_USER, DB_PASS) or die(mysql_error());  mysql_select_db(DB_NAME) or die("Cannot select DB");  ?>  

Notice that you require constants.php. This will make sure to stop the script and will produce an error if there is any.

Include the connection.php to login.php and register.php file since these two files need connection-driven codes. Copy the code below and paste it above the header.php include code.

  <?php require_once("includes/connection.php"); ?>  

Step – 6 Configuring register.php File

Now its time to convert the registration form into a complete registration system. To achieve that, you need to add more PHP files under the header.php include file. Copy and paste the code below.

  <?php    if(isset($_POST["register"])){    if(!empty($_POST['full_name']) && !empty($_POST['email']) && !empty($_POST['username']) && !empty($_POST['password'])) {              	$full_name=$_POST['full_name'];              	$email=$_POST['email'];              	$username=$_POST['username'];              	$password=$_POST['password'];                	$query=mysql_query("SELECT * FROM usertbl WHERE username='".$username."'");              	$numrows=mysql_num_rows($query);                	if($numrows==0)              	{              	$sql="INSERT INTO usertbl                                              	(full_name, email, username,password)                                              	VALUES('$full_name','$email', '$username', '$password')";                	$result=mysql_query($sql);                	if($result){              	 $message = "Account Successfully Created";              	} else {              	 $message = "Failed to insert data information!";              	}                	} else {              	 $message = "That username already exists! Please try another one!";              	}    } else {              	 $message = "All fields are required!";  }  }  ?>    <?php if (!empty($message)) {echo "<p class=\"error\">" . "MESSAGE: ". $message . "</p>";} ?>  

On the code above, notice that validations were used first before inserting data to the database. Also, the message variable was used to hold the error or success messages.

Step – 6 Configuring login.php File

Now that users can register on the site, you need to create the login system. By using this very simple PHP code below, you can enable the login system. Copy the code below and paste it to above the markup of our login.php file.

  <?php  session_start();  ?>    <?php require_once("includes/connection.php"); ?>  <?php include("includes/header.php"); ?>    <?php    if(isset($_SESSION["session_username"])){  // echo "Session is set"; // for testing purposes  header("Location: intropage.php");  }    if(isset($_POST["login"])){    if(!empty($_POST['username']) && !empty($_POST['password'])) {  	$username=$_POST['username'];  	$password=$_POST['password'];    	$query =mysql_query("SELECT * FROM usertbl WHERE username='".$username."' AND password='".$password."'");    	$numrows=mysql_num_rows($query);  	if($numrows!=0)    	{  	while($row=mysql_fetch_assoc($query))  	{  	$dbusername=$row['username'];  	$dbpassword=$row['password'];  	}    	if($username == $dbusername && $password == $dbpassword)    	{    // old placement  //	session_start();  	$_SESSION['session_username']=$username;    	/* Redirect browser */  	header("Location: intropage.php");  	}  	} else {  //	$message = "Invalid username or password!";    echo  "Invalid username or password!";  	}    } else {  	$message = "All fields are required!";  }  }  ?>    

In the code above, you should check first if the session was set before redirecting the user to the intropage.php, which you will be adding later.

Otherwise, if it is not set. It will display the error through the message variable or redirect the user to login.php itself.

Step – 7 Configuring intropage.php File

All set is set for the register.php and login.php file. Now you just need to make sure that the user will stay login to the intropage.php if the session is set. Copy and paste the code below to the intropage.php.

  <?php  session_start();  if(!isset($_SESSION["session_username"])) {              	header("location:login.php");  } else {  ?>    <?php include("includes/header.php"); ?>  <div id="welcome">              	<h2>Welcome, <span><?php echo $_SESSION['session_username'];?>! </span></h2>              	<p><a href="logout.php">Logout</a> Here!</p>  </div>    <?php include("includes/footer.php"); ?>    <?php  }  ?>  

Notice that an if statement was created to test if the session was set or not so you can decide if the user will be redirected to login.php or stay on the intropage.php.

Step – 8 Configuring logout.php File

Finally, for the user to be able to logout, you need to destroy the session using the session_destroy.

Go ahead and copy the code below to the logout.php.

  <?php  session_start();  unset($_SESSION['session_username']);  session_destroy();  header("location:login.php");  ?>  

Wrapping Up

Today you learned how to create a simple login system using PHP and MySQL. Although there are a lot things to consider when it comes to security, this is already a good start for beginners.

You are free to modify the use the codes above on your project. If you have any idea to improve the codes, please free to drop a comment on the comment section below.

Hope you enjoyed this tutorial and learn something. See you again next time!

No comments:

Post a Comment