User Signup and Login with PHP

Creating user login system is one of the most interesting thing for developers. If you want to create a web application with user sign up and sign in system or even if you want to create a secure admin area this method can help you a lot.

Today we are going to create a simple application with php that can allow a user to sing up, sign in and viewing secure page.

Live Demo Download Source

Step 1 - Database

In this tutorial we are going to use MySQL database based user login system.

Users table

At first we need to create users database table. This table has two fields (username & password) with an auto increment filed (id).

CREATE TABLE `users` (
  `id` int(6) NOT NULL AUTO_INCREMENT,
  `username` varchar(16) NOT NULL,
  `password` varchar(40) NOT NULL,
  PRIMARY KEY (`id`)
);

Database connection

In this tutorial we are going to use PDO (PHP Data Object) to do database queries. If you are not familiar with PDO I recommend you to read this article at first.

function dbconnect()
{
  global $pdo;

  try {
    $pdo = new PDO('mysql:host=localhost;dbname=mydb', 'root', 'root');
  } catch (PDOException $e) {
    die('MySQL connection fail! ' . $e->getMessage());
  }
}

The dbconnect function will establish database connect. In here you will need to change host name, dbname, username and password.



Step 2 - User Signup

We will allow new users to signup in this tutorial. In this section will will create a user signup system.

Signup HTML

To create a user signup system at first we will need to create a signup form. The following html code is placed in signup.php file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sign Up</title>
</head>
<body>
  <h1>Sign Up</h1>
  <p>Already have an account? <a href="signin.php">Login</a></p>
  <!-- error or success message will be shown here -->
  <?php if (!empty($_GET['error'])): ?>
    <p><?php echo $_GET['error']?></p>
  <?php endif ?>
  <?php if (!empty($_GET['success'])): ?>
    <p><?php echo $_GET['success']?></p>
  <?php endif ?>

  <!-- signup form -->
  <form action="signup_post.php" method="post">
    <input type="text" name="username" placeholder="username">
    <input type="password" name="password" placeholder="password">

    <input type="submit" value="Sign Up">
  </form>
</body>
</html>

Insert new user information

The insert_new_user function inserts new user's data to the database.

function insert_new_user($username, $password)
{
  # checking username is already taken
  if (username_exists($username))
    return false;

  # insert new user info
  global $pdo;
  $stmt = $pdo->prepare('
    INSERT INTO users
    (username, password)
    values (:username, :password)');

  $stmt->execute( array(':username' => $username, ':password' => md5($password)) );

  if ($pdo->lastInsertId())
    return true;
  else
    return false;
}



Step 3 - Sign in

Now we are going to create user sign in system. This system is based on PHP session function.

Sign in HTML

The sign in form is almost same as sing up form and it is placed in singin.php file.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Sign In</title>
</head>
<body>
  <h1>Sign In</h1>

  <!-- error or success message will appear here -->
  <?php if (!empty($_GET['error'])): ?>
    <p><?php echo $_GET['error']?></p>
  <?php endif ?>

  <!-- sign in form -->
  <form action="sign_post.php" method="post">
    <input type="text" name="username" placeholder="username">
    <input type="password" name="password" placeholder="password">

    <input type="submit" value="Sign In">
  </form>

</body>
</html>

Sign in attempt function

The attempt function attempts to sign in users. If a user requests to sign in by his username & password it looks into users table on database and if it founds everything ok it sets username to the session variable and returns true.

function attempt($username, $password)
{
  global $pdo;
  
  $stmt = $pdo->prepare('
    SELECT id, username
    FROM users
    WHERE username = :username AND password = :password
    LIMIT 1');

  $stmt->execute(array(':username' => $username, 'password' => md5($password)));

  if ($data = $stmt->fetch( PDO::FETCH_OBJ )) {
    # set session
    $_SESSION['username'] = $data->username;
    return true;
  } else {
    return false;
  }
}

10 comments:

  1. thanks this is a great easy to understand tutorial

    ReplyDelete
  2. 1- Don't use global
    2 - MD5 is a weak hashing algorithm. You should be using crypt()
    3 - use html5 attribute 'require' to force/validate user to enter only email, pass, url types
    4 - use PDO with proper emulation, and error mode exception..

    ReplyDelete
  3. I really do agree on this never use global.
    MD5 is a weak hash algorithm but accepted by large, but crypt really should be used instead.
    yes you could use the html5 attribute require but we still struggle with the the end client to have a up to date browser.

    ReplyDelete
  4. Dear Resalat Haque
    i need some help i n this tutorial can u please help me

    ReplyDelete
  5. Thank you very much for great support.

    ReplyDelete
  6. Ace Maxs Asli Di Apotik K24 - Selain di apotik k24 juga ace maxs asli bisa anda dapatkan disini

    ReplyDelete

Go to top