Skip to main content

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;
  }
}

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
  7. Very good informative article. Thanks for sharing such nice article, keep on up dating such good articles.

    NO.1 AQM Services | Application Quality Managment Services | Austere Technologies

    ReplyDelete
  8. wow...nice blog, very help full information. Thanks for sharing.
    NO.1 API DEVELOPMENT SERVICES | MASSIL TECHNOLOGIES

    ReplyDelete

Post a Comment

Popular posts from this blog

Multiple File Upload with Progress Bar using PHP & jQuery

Some days age I have created a post that deals with How we can upload file with progress bar using php and jQuery. Some of my readers asked me how we can upload multiple files with progress bar. In this post I am going to show you how we can upload multiple files with progress bar.We can upload multiple files with progress bar exactly same way as I shown previous. But we need to do some modification with our file upload form and our php script to handle multiple files.

Force File Download with PHP

If you want to control or track your downloadable contents then a force file downloader script can give you more option. Especially if you want make images or other stemming contents like music file (mp3, wav, ogg), video files (flv, mp4, ogg, 3gpp), css, JavaScripts or even a php file downloadable then you must need to use a force file downloader script.
In this post I am going to share a simple but useful force file downloader script.

File Upload with Progress Bar using jQuery and PHP

In this post you will learn how to create a AJAX file uploading system with progress bar using jQuery and PHP. For this purpose we will going to use jQuery Form Plugin. It is a easy to use and powerful jQuery AJAX form submitting plugin. It supports XMLHttpRequest Level 2 and iframe file transportation. That's why it will work for both old and new browsers.