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
  9. Good article and knowledge for me! I found a lot of information here! This article is really good for all newbie here. Thank you for sharing with us!
    vex 3

    ReplyDelete

Post a Comment

Popular posts from this blog

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

Live Comment System with jQuery Ajax PHP and MySQL

Recently I have been made a post that focused on how to submit form without page refreshing. That post shows the basic functionality of using jQuery Ajax. On the same follow this post will describe how we can create a comment system to post an instant comment without page refreshing. Let's start...

Resize Image While Uploading with PHP

On my previous post I was shown an example how to upload file with php and html. It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading. Suppose if you run a website and want to allow users to upload image files than you need to think little bit about server's space and bandwidth. For this purpose you need to do some optimization with image files. Image resize while uploading is one of them. All major website do it in the same way. If a user uploads a 5mb image file they resize it in different sizes and store on there server. It helps them to seed up there website and reduce there budget. Now take a look, how we can do it ourself.