How to create a membership system for your website with PHP 5.6


#1

INTRODUCTION


In this tutorial, we will learn how to create a membership system (login/signup) for your website, using PHP.

BEFORE WE BEGIN


Before we begin with this tutorial, make sure:

+You have set your PHP version to 5.6 or higher
          To do this, go to your cPanel, then navigate to ‘Settings’ >>
           ‘General’ >> ‘Scroll down’ >> ‘PHP Version’ >> ‘5.6’

+You have created a database
          To do this, go to your cPanel, click on Manage databases, then
          create a database. Save you database credentials somewhere,
          because we will use them later.

+You have added this line of code to the .htaccess
php_flag output_buffering on

THE TUTORIAL


THE DATABASE


  1. Go to 000Webhost phpMyAdmin, and login with your database credentials.

  2. Click on the database (e.g. id3456_cksoft), then click on SQL and paste the following code into it

    CREATE TABLE IF NOT EXISTS `users` (
      `userId` int(11) NOT NULL AUTO_INCREMENT,
      `userName` varchar(30) NOT NULL,
      `userEmail` varchar(60) NOT NULL,
      `userPass` varchar(255) NOT NULL,
      PRIMARY KEY (`userId`),
      UNIQUE KEY `userEmail` (`userEmail`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

Then click on Go

Conclusion:

We have created a table called users, where we will store the user information.

The HTML & PHP


Connecting to the database

Create a file called dbconnect.php and add the following code into it

<?php

 error_reporting( ~E_DEPRECATED & ~E_NOTICE );
 
 define('DBHOST', 'localhost');
 define('DBUSER', 'root');
 define('DBPASS', '1234');
 define('DBNAME', 'dbtest');
 
 $conn = mysqli_connect(DBHOST,DBUSER,DBPASS);
 $dbcon = mysqli_select_db($conn,DBNAME);
 
 if ( !$conn ) {
  die("Connection failed : " . mysqli_error());
 }
 
 if ( !$dbcon ) {
  die("Database Connection failed : " . mysqli_error());
 }
?>

Now, replace:
+DBUSER with your database user found in ‘cPanel’ >> ‘Manage databases’.
+DBPASS with your database password.
+DBNAME with your database name found in ‘cPanel’ >>‘Manage databases’.


### **The login page**

Create a file called login.php, and add the following code to it

<?php
     ob_start();
     session_start();
     include_once 'dbconnect.php';

     if ( isset($_SESSION['user'])!="" ) {
      header("Location: home.php");
      exit;
     }
     
     $error = false;
     
     if( isset($_POST['btn-login']) ) { 
      
      $email = trim($_POST['email']);
      $email = strip_tags($email);
      $email = htmlspecialchars($email);
      
      $pass = trim($_POST['pass']);
      $pass = strip_tags($pass);
      $pass = htmlspecialchars($pass);
      
      if(empty($email)){
       $error = true;
       $emailError = "Please enter your email address.";
      } else if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
       $error = true;
       $emailError = "Please enter a valid email address.";
      }
      
      if(empty($pass)){
       $error = true;
       $passError = "Please enter your password.";
      }
      
      if (!$error) {
       
       $password = hash('sha256', $pass);
      
       $res=mysqli_query($conn,"SELECT userId, userName, userPass FROM users WHERE userEmail='$email'");
       $row=mysqli_fetch_array($res);
       $count = mysqli_num_rows($res);
       
       if( $count == 1 && $row['userPass']==$password ) {
        $_SESSION['user'] = $row['userId'];
        header("Location: home.php");
       } else {
        $errMSG = "Incorrect Credentials, Please try again...";
       }
        
      }
      
     }
    ?>
    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>000Webhost membership system</title>
    </head>
    <body>

    <div class="container">

     <div id="login-form">
        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">
        
         <div class="col-md-12">
            
             <div class="form-group">
                 <h2 class="">Sign In.</h2>
                </div>
            
             <div class="form-group">
                 <hr />
                </div>
                
                <?php
       if ( isset($errMSG) ) {
        
        ?>
        <div class="form-group">
                 <div class="alert alert-danger">
        <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
                    </div>
                 </div>
                    <?php
       }
       ?>
                
                <div class="form-group">
                 <div class="input-group">
                    <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
                 <input type="email" name="email" class="form-control" placeholder="Your Email" value="<?php echo $email; ?>" maxlength="40" />
                    </div>
                    <span class="text-danger"><?php echo $emailError; ?></span>
                </div>
                
                <div class="form-group">
                 <div class="input-group">
                    <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
                 <input type="password" name="pass" class="form-control" placeholder="Your Password" maxlength="15" />
                    </div>
                    <span class="text-danger"><?php echo $passError; ?></span>
                </div>
                
                <div class="form-group">
                 <hr />
                </div>
                
                <div class="form-group">
                 <button type="submit" class="btn btn-block btn-primary" name="btn-login">Sign In</button>
                </div>
                
                <div class="form-group">
                 <hr />
                </div>
                
                <div class="form-group">
                 <a href="signup.php">Sign Up Here...</a>
                </div>
            
            </div>
       
        </form>
        </div> 

    </div>

    </body>
    </html>
    <?php ob_end_flush(); ?>

The signup page

Create a file called signup.php, and add the following code to it

<?php
 ob_start();
 session_start();
 if( isset($_SESSION['user'])!="" ){
  header("Location: home.php");
 }
 include_once 'dbconnect.php';

 $error = false;

 if ( isset($_POST['btn-signup']) ) {
  
  $name = trim($_POST['name']);
  $name = strip_tags($name);
  $name = htmlspecialchars($name);
  
  $email = trim($_POST['email']);
  $email = strip_tags($email);
  $email = htmlspecialchars($email);
  
  $pass = trim($_POST['pass']);
  $pass = strip_tags($pass);
  $pass = htmlspecialchars($pass);
  
  if (empty($name)) {
   $error = true;
   $nameError = "Please enter your full name.";
  } else if (strlen($name) < 3) {
   $error = true;
   $nameError = "Name must have atleat 3 characters.";
  } else if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
   $error = true;
   $nameError = "Name must contain alphabets and space.";
  }
  
  if ( !filter_var($email,FILTER_VALIDATE_EMAIL) ) {
   $error = true;
   $emailError = "Please enter valid email address.";
  } else {
   $query = "SELECT userEmail FROM users WHERE userEmail='$email'";
   $result = mysqli_query($conn,$query);
   $count = mysqli_num_rows($result);
   if($count!=0){
    $error = true;
    $emailError = "Provided Email is already in use.";
   }
  }
  if (empty($pass)){
   $error = true;
   $passError = "Please enter password.";
  } else if(strlen($pass) < 6) {
   $error = true;
   $passError = "Password must have atleast 6 characters.";
  }
  
  $password = hash('sha256', $pass);
  
  if( !$error ) {
   
   $query = "INSERT INTO users(userName,userEmail,userPass) VALUES('$name','$email','$password')";
   $res = mysqli_query($conn,$query);
    
   if ($res) {
    $errTyp = "success";
    $errMSG = "Successfully registered, you may login now";
    unset($name);
    unset($email);
    unset($pass);
   } else {
    $errTyp = "danger";
    $errMSG = "Something went wrong, try again later..."; 
   } 
    
  }
  
  
 }
?>
<!DOCTYPE html>
<html>
<head>
<title>Sign Up - 000webhost membership system</title>
</head>
<body content="width=device-width,initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<center>
    <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">             <h2 class="">Sign Up.</h2>
             <hr />
            <?php
   if ( isset($errMSG) ) {
    
    ?>
    <span class="glyphicon glyphicon-info-sign"></span> <?php echo $errMSG; ?>
                </div>
             </div>
                <?php
   }
   ?>
            
                <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
             <input type="text" name="name" class="form-control" placeholder="Enter Name" maxlength="50" value="<?php echo $name ?>" />
                <span class="text-danger"><?php echo $nameError; ?></span>
            <br>
                <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span></span>
             <input type="email" name="email" class="form-control" placeholder="Enter Your Email" maxlength="40" value="<?php echo $email ?>" />
                <span class="text-danger"><?php echo $emailError; ?></span>
            </div>
            <br>
                <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
             <input type="password" name="pass" class="form-control" placeholder="Enter Password" maxlength="15" />
                <span class="text-danger"><?php echo $passError; ?></span>
            <br>
            <div class="form-group">
             <hr />
             <button type="submit" class="btn btn-block btn-primary" name="btn-signup">Sign Up</button>
             <hr />
             <a href="login.php">Already have an account? Sign in !</a>
    </form> 
  </center>
</body>
</html>
<?php ob_end_flush(); ?>

The home page

After a successful login, the user will be redirected to a page called home page. Create a file called home.php and add the following code to it

<?php
 ob_start();
 session_start();
 require_once 'dbconnect.php';
 
 if( !isset($_SESSION['user']) ) {
  header("Location: login.php");
  exit;
 }
 $res=mysqli_query($conn,"SELECT * FROM users WHERE userId=".$_SESSION['user']);
 $userRow=mysqli_fetch_array($res);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Welcome - <?php echo $userRow['userName']; ?></title>
</head>
<body>

<h1>This page is only visible for logged in users<h1>
<a href="logout.php?logout">Logout</a>
</body>
</html>
<?php ob_end_flush(); ?>

###**The logout page**

Create a file called logout.php and add the following code to it

<?php
 session_start();
 if (!isset($_SESSION['user'])) {
  header("Location: index.php");
 } else if(isset($_SESSION['user'])!="") {
  header("Location: home.php");
 }
 
 if (isset($_GET['logout'])) {
  unset($_SESSION['user']);
  session_unset();
  session_destroy();
  header("Location: login.php");
  exit;
 }
?>

Conclusion:


We have created 5 files: +dbconnect.php to connect to the database and select the correct database +login.php for the users to login +signup.php for the users to signup +home.php for logged in users +logout.php to logout users

TO NOTE


Add this piece of code at the top of each page you want logged in users only to access

<?php
 ob_start();
 session_start();
 require_once 'dbconnect.php';
 
 if( !isset($_SESSION['user']) ) {
  header("Location: index.php");
  exit;
 }
 $res=mysqli_query($conn,"SELECT * FROM users WHERE userId=".$_SESSION['user']);
 $userRow=mysqli_fetch_array($res);
?>

IN THE END


Hope you enjoyed this tutorial, and if it worked for you, give it a thumbs up by clicking the like button.
If you need any more help, you can create a new topic here, and we will be happy to help you!


PHP Error with creating Log In
Help me out my my login.php page I can Get into login page
Someone could help (PHP Register)
How to add login script in website
Php and sql registration form on already existing db
Problem with hash
I want to create user profile by retriving data from mysql
Help with creating HTML page
#8

this is my validation page


<?php
function error_found(){
header(“Location: login.php”);
}
set_error_handler(‘error_found’);
?>
<?php
$con=mysqli_connect(‘localhost’,‘root’,’’,‘mydb’);
session_start();
if(isset($_POST[‘loginbtn’])){
$email=$_POST[‘email’];
$password=$_POST[‘pwd’];
$result=mysqli_query($con,‘select * from myguests where email="’.$email.’" and password="’.$password.’"’);
if(mysqli_num_rows($result)==1)
{
$_SESSION[‘email’]= $email;
header(“Location: welcome.php”);
}
else
echo"INVALID ACCOUNT";

}

?>

</body>
</html>

this is my user profile page

<?php    
 require_once 'valid.php'; 
    session_start();    
echo"welcome  " .$_SESSION['email'];
$res=mysqli_query($conn,"SELECT * FROM MyGuests WHERE email=".$_SESSION['email']);
 $userRow=mysqli_fetch_array($res);
 echo $userRow;
?>
<br><a href="logout.php">logout</a>
</body>
</html>

i cannot able to fetch the data from data base it show me the error


#9

Follow the tutorial above to get it working better :slight_smile:


#11

1-how to do manage database?

2- Why say as image when I’m registering


#12

Add following code to the .htaccess file in the root.

php_value display_errors 1

Then it might show an error.


#13

This tutorial has so many serious security errors, I don’t know where to begin. Over on Stack Overflow, we spend a great deal of time trying to rescue beginners from producing software with such problems, often to little avail. Dealing with bad security advice is like a game of whack-a-mole - educate one user, and several more insecure implementations pop up. Tutorials like this are the reason why.

The main problem here is SQL injection, which is bad enough. Read more here about how to prevent this.

It’s good that passwords are hashed, but they’re not salted, so they’re probably susceptible to reverse-engineering using rainbow tables. I don’t know what the advice is about the suitability of SHA256, but the PHP core team recommend Bcrypt (or the more recently added Argon2). So, unless you really know what you’re doing, use password_hash().

Also, there’s no reason to recommend PHP 5.6. Version 7.1 seems to be the 000webhost default - encourage people to use that. When 7.2 comes out on the 000webhost platform, edit your material to ensure readers use that instead. Make sure your code runs on both, of course.

There’s another curious bug, which means that if I choose this password:

X<Wan7^&X@h87(&Bp?[i7841+lCXFC~]kXl=y60V&

Then I will be able to log in using a password of:

X

which renders my complex password useless, and very breakable.

Can anyone spot why?


#14

We’re gona fix the security holes (once my ISP brings my internet connection back alive)


#15

Excellent, thanks! I look forward to seeing the changes.


#16

May not be soon (as my ISP is so busy), but they will be changed sooner or later, just no ETA.