WHAT'S NEW?

(Source files) How to create a login and register system with PHP and MySQLi (PHP tutorial)

In this tutorial, we will see how sessions works in addition to storing and getting records from database. then checking records are they available or not.



this tutorial has fondamentale of creating login and register forms and make them work.



First take a look at the demo:

So for the HTML and CSS part we will work on an already made Form download it from here:
  

Download files to your computer, run your localhost server and let's start coding.

PART I: Creation of database

So what we are going to need is two fields, username and password.
Create a new database and call it -log- and inside of it table and call it -users- then two fields -username- and -password- like that:


 You can created this on your own way or just download the SQL file from here and import it into you SGBD.

PART II: Connecting database with the script

So for connecting all script pages we need to create another file db.php and include it to all other pages, so create a new db.php file and write down this code.





<?php
$con = mysqli_connect("localhost","root","","log");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
  
?>

To understand the code please check the previous tutorial from here:

http://www.digitalservicesmarket.biz/2015/09/source-files-how-to-create-commenting.html

now we should include the db.php or the connection file into all other pages, all what we are going to do is to past the next code at the top of the following files: login.php, index.php, register.php and not need to add it to the logout.php:



<?php include('db.php'); ?>

Now database connection part is finished Yaay :D

PART III: Register form add new users to the table

in this part we will manage new users, so users need to give there informations ( username and password) check them and store them in database.

so open the register.php file and let's do something work.

let's edit our form and make the action after sending form to regsiter.php?new=1, it a little complicated to understand why now but at the finish of the tutorial you'll understand, don'y worry.

the form code should be like that:


<form method="post" action="register.php?new=1" class="login">

Now we should make register.php?new=1 page get data and store it in the database.

so we make a call to the page, insert this code into your register.php file:


<?php if (isset($_GET['new']) && is_numeric($_GET['new']) && $_GET['new']==1){
  
  // parameters of register.php?new=1 
 } ?>

So the explanation of the code is  if the page has new as an argument that is ?new and new equal to a number that is 1 do the following instruction, here we made a call to the new page inside the register page.
so the instruction are to get data from the registering form then, check if they are not empty and store them at the database using SQL query.
let's translate that to a php code first get data from form.



//1st getting data
$username = (htmlspecialchars($_POST['login']));
$password = (htmlspecialchars($_POST['password']));

And we check if they are not empty with the classic function if:



if($username=='' || $password==''){ // if the two fields are empty
   echo 'username and password are required';
  }else{
   //if everything is okey
   
  }
Good now we use MySqli query to put them in database.



mysqli_query($con,"INSERT users SET username='$username', password='$password'")
 or die(mysql_error()); 

So after data is stored user should be redirected into login.php using headers so all code will be:



<?php if (isset($_GET['new']) && is_numeric($_GET['new']) && $_GET['new']==1){
  
  // parameters of register.php?new=1 
  //1st getting data
  $username = (htmlspecialchars($_POST['login']));
  $password = (htmlspecialchars($_POST['password']));
  
  if($username=='' || $password==''){ // if the two fields are empty
   echo 'username and password are required';
  }else{
   //if everything is okey
   mysqli_query($con,"INSERT users SET username='$username', password='$password'")
 or die(mysql_error()); 
 echo 'good';
 echo $username;
  }
  
 } ?>

to read more about how we store data please check this previous tutorial:

(Source files) How to create a commenting system using php and MySql (php tutorial)


PART III: Login form and checking username and password

In this part we will get data from login.php form and testing if data are in database or not.
so in the login.php we made some changes here like the action of the form we will make it to login.php?check=1

so we are going to do the same as we have done in register part:


<?php if (isset($_GET['check']) && is_numeric($_GET['check']) && $_GET['check']==1){
  
  
  //1st getting data
  $username = (htmlspecialchars($_POST['login']));
  $password = (htmlspecialchars($_POST['password']));
  
  if($username=='' || $password==''){ // if the two fields are empty
   echo 'username and password are required to log in';
  }else{
   //if everything is okey let's check if they are exist in data base
   
  }
  
 } ?>

now in the else{} part we will check if they are in database, first we need to explore database and check if they are exist with query.



$result=mysqli_query($con,"SELECT * FROM users WHERE username='$username' AND password='$password'");
            $login = $result->num_rows;
This query calculate how many rows in database has the username and password the user intred so if login equal to 0, the password and user are not in database and if it equal to 1 so user and pass are in.

So if login equal to 1 user must login, else he don't have permission.

translate into php.




if($login==1){
    // Good you are logged in redirect to home page
   }else{
    // check your username and password and try again
   }
PART IV: Sessions and login details

what are session in php?
When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn't maintain state.

so we need to start session and store username and password in session variables, 



session_start();
    $_SESSION["username"]=$username;
    $_SESSION["password"]=$password;

now username and password are stored in two session variables then we redirect users to index.php.

in the else part we just advising users to recheck ther details.
All php code would be like that:


<?php if (isset($_GET['check']) && is_numeric($_GET['check']) && $_GET['check']==1){
  
  // parameters of register.php?new=1 
  //1st getting data
  $username = (htmlspecialchars($_POST['login']));
  $password = (htmlspecialchars($_POST['password']));
  
  if($username=='' || $password==''){ // if the two fields are empty
   echo 'username and password are required to log in';
  }else{
   //if everything is okey let's check if they are exist in data base
   $result=mysqli_query($con,"SELECT * FROM users WHERE username='$username' AND password='$password'");
            $login = $result->num_rows;
   
   if($login==1){
    // Good you are logged in redirect to home page
    session_start();
    $_SESSION["username"]=$username;
    $_SESSION["password"]=$password;
    header('location: index.php');
   }else{
    // check your username and password and try again
    echo 'check details and try again';
   }
  }
  
 } ?> 
PART V: Home page security

For the home page or index.php, only logged in user could get into it. let's add security codes:

in index.php code we start the session and try to test if session variable are empty so user must login else user can stay.

So open the index.php file and let's write down this small code:



<?php
session_start();
if($_SESSION['username']=='' || $_SESSION['password']==''){
 header('location: login.php');
}
?>
Great!
PART VI: Destroying sessions and logout function
for the logout page it's just about destroying sessions and variable so we will put this code in the logout.php file:



<?php
// remove all session variables
session_unset(); 

// destroy the session 
session_destroy(); 
header('location: index.php'); /*this is to redirect to the main page as the session is
destroyed it will be redirected to the login page */
?>

so everything is works good now.
PART VI: Additionnelle tricks must be added.

Now if someone has potted the same username as another this part should be managed.
so what we are going to check if username already exist in database, we tell user to choose another one, let's go back to register.php and add this function.
query is to select all rows where username as it puted by user if number of rows is not equal to 0 means that user already exist so check that code you'll understand, so all php code in register.php would be like that:





<?php if (isset($_GET['new']) && is_numeric($_GET['new']) && $_GET['new']==1){
  
  // parameters of register.php?new=1 
  //1st getting data
  $username = (htmlspecialchars($_POST['login']));
  $password = (htmlspecialchars($_POST['password']));
  
  if($username=='' || $password==''){ // if the two fields are empty
   echo 'username and password are required';
  }else{
   //if everything is okey
   $result=mysqli_query($con,"SELECT * FROM users WHERE username='$username'");
            $users = $result->num_rows;
   if($users!=0){
    echo ' User already exist check another one please';
   }else{
   mysqli_query($con,"INSERT users SET username='$username', password='$password'")
 or die(mysql_error()); 
 echo 'good';
 echo $username;
  }}
  
 } ?> 

Another thing, is people are logged shouldn't get into register page, so the same code as index.php, but this time if session variable are not empty go to the index.



<?php
session_start();
if($_SESSION['username']!='' || $_SESSION['password']!=''){
 header('location: index.php');
}
?>

The same code must be putted in login.php.

Great News this is the final step in this tutorial you have made your own login and register system with php and mysql database.

Download source file and don't forget to share this article.


Don't forget to share this on facebook twitter or google+ and subscribe to get everything new tutorial with source files.



If you have any questions, please feel free to add comments.

and share with us your experience with php and web developement.

2 comments: Leave Your Comments

  1. This article is good . For more detail in briefly click here

    HOW TO CREATE A SESSION IN PHP

    ReplyDelete
  2. Wow what a great blog, i really enjoyed reading this, good luck in your work. Homepage Berlin

    ReplyDelete

Thank for leaving a comment