Making a login form using PHP

This is in continuation of the tutorial on making a membership based web site. Please see the previous page PHP registration form for more details.

Download the code

You can download the whole source code for the registration/login system from the link below:
RegistrationForm.zip
The ReadMe.txt file in the download contains detailed instructions.

The login form

PHP login form

Here is the HTML code for the login form.

<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<fieldset >
<legend>Login</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>

<label for='username' >UserName*:</label>
<input type='text' name='username' id='username'  maxlength="50" />

<label for='password' >Password*:</label>
<input type='password' name='password' id='password' maxlength="50" />

<input type='submit' name='Submit' value='Submit' />

</fieldset>
</form>

Logging in

We verify the username and the password we received and then look up those in the database. Here is the code:

function Login()
{
    if(empty($_POST['username']))
    {
        $this->HandleError("UserName is empty!");
        return false;
    }
    
    if(empty($_POST['password']))
    {
        $this->HandleError("Password is empty!");
        return false;
    }
    
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
    
    if(!$this->CheckLoginInDB($username,$password))
    {
        return false;
    }
    
    session_start();
    
    $_SESSION[$this->GetLoginSessionVar()] = $username;
    
    return true;
}

In order to identify a user as authorized, we are going to check the database for his combination of username/password, and if a correct combination was entered, we set a session variable.

Here is the code to look up the username and password.

function CheckLoginInDB($username,$password)
{
    if(!$this->DBLogin())
    {
        $this->HandleError("Database login failed!");
        return false;
    }          
    $username = $this->SanitizeForSQL($username);
    $pwdmd5 = md5($password);
    $qry = "Select name, email from $this->tablename ".
        " where username='$username' and password='$pwdmd5' ".
        " and confirmcode='y'";
    
    $result = mysql_query($qry,$this->connection);
    
    if(!$result || mysql_num_rows($result) <= 0)
    {
        $this->HandleError("Error logging in. ".
            "The username or password does not match");
        return false;
    }
    return true;
}

Please notice that we must compare the value for the password from the database with the MD5 encrypted value of the password entered by the user. If the query returns a result, we set an “authorized” session variable, and then redirect to the protected content. If there are no rows with the entered data, we just redirect the user to the login form again.

Access controlled pages

For those pages that can only be accessed by registered members, we need to put a check on the top of the page.
Notice that we are setting an “authorized” session variable in the login code above. On top of pages we want to protect, we check for that session variable. If user is authorized, we show him the protected content, otherwise we direct him to the login form.

Include this sample piece of code on top of your protected pages:

<?PHP
require_once("./include/membersite_config.php");

if(!$fgmembersite->CheckLogin())
{
    $fgmembersite->RedirectToURL("login.php");
    exit;
}
?>

See the file: access-controlled.php in the downloaded code for an example.

Here is the CheckLogin() function code.

function CheckLogin()
{
     session_start();

     $sessionvar = $this->GetLoginSessionVar();
     
     if(empty($_SESSION[$sessionvar]))
     {
        return false;
     }
     return true;
}

These are the basics of creating a membership site. Now that you have the basic knowledge, you can experiment with it and add new features, such as a “Forgot password” page to allow the user to retrieve or change his password if he forgets it.

Updates

9th Jan 2012
Reset Password/Change Password features are added.
The code is now shared at GitHub.

License


The code is shared under LGPL license. You can freely use it on commercial or non-commercial websites.

Comments on this entry are closed.

  • thanks for sharing this info……..i read this and got lot’s more about login.

  • Has anyone ever figured out the “Failed sending registration confirmation email.” problem?
    I have the same issue.

    • Fixed it! Changed server name on line 237 in the file €˜fg_membersite.php€™
      from: $host = $_SERVER[‘SERVER_NAME’];
      to: $host = $_SERVER[‘localhost’];

      Great code, works perfectly now, except when new users clicks the confirmation link twice. Need to work on that unless someone has already fixed that.

  • Nice tutorial..it’s help.

  • Dear All.
    I am New to PHP.
    I have created two Tables in a DB(Members & DailySales)
    I want to create a login page so that onle the loggedin member can see their data only from table DailySales.
    and admin can see all the Members Sales
    I did manage to create a Login page and its working , but when MemberX login , he can see all the Data of DailySales table.
    Please help me in this simple project.
    MemberX can see only X data and MemberY can see Y data and so on.
    Admin can see all Data

    Regards

    Rabi

    • u just need to create admin_login page…then only admin can see all the details

  • Hello,

    It’s very nice, thank you!
    One question: How can I use it with http/https change?
    So login page is: https://secure.com/login.php, but product pages are like:
    http://product.com/access-controlled.php on the same server?

    Thanks in advance. Yoli

  • I get the following error:
    Warning: mysql_connect() [function.mysql-connect]: Can’t connect to local MySQL server through socket ‘/var/lib/mysql/mysql.sock’ (2) in /home/content/t/t/s/ttservices/html/webauthorsgroup/testpage/source/include/fg_membersite.php on line 513

    Line 513 is this: $this->connection = mysql_connect($this->db_host,$this->username,$this->pwd);

    db_host is where I am confused as I think it is my host: h41mysql5.secureserver.net, but this is wrong too – can anyone help?

    Thanks in advance,
    Bruce

    • db_host is the host name u a can give it as localhost in ur MySql (privileges).

  • ok, I figured it out by reinstalling all the files – NOTE TO EVERYONE WHO EXPERIENCE THE “ERROR ON LINE 513” MESSAGE:

    ONLY edit the following file:
    1. Edit the file membersite_config.php in the includes folder and
    update the configuration information (like your email address, Database login etc)

    Do NOT touch any other file unless specified under the READ ME file included in the installation zip file.

    -Bruce

  • Hi. I was able to implement all the forms and the code is working properly. I even received the notifications emails as programmed. I noticed that once the users log in all of them are redirected to the same generic page. What I need is for each user logged in taken to their own user specific page and no one else have access to it. Is there a way to accomplish this fairly easily? Thanks in advance for any help and tutorials.

  • Hi:

    I need scripts to create a form or a page to enable a user access the home page of a Web site after logging in.

    Thank you very much in advance.

  • @Frankie

    Your solution doesnt work? I get the error “unidentified index on line … ‘localhost’..” if I adapt the changes as you have mentioned in your post.

    Anybody has another solution or am I doing something wrong?:

    function GetFromAddress()
    {
    if(!empty($this->from_address))
    {
    return $this->from_address;
    }

    $host = $_SERVER[‘localhost’];

    $from =”nobody@$host”;
    return $from;
    }

  • How can we get all this script in one page only???

  • I’m having trouble adding a space between 2 variables, For instance, first name, and last name which sends both a confirmation message, and a you have completed registration email.

    The variables are added to the message, but need a space between them.

    What is the syntax to be added to this line of code to add a space between the firstname, and lastname
    $mailer->Body =”Hello “.$user_rec[‘firstname’].$user_rec[‘lastname’].”\r\n\r\n”.

  • In the admin notification email, I would like to have the Event (place where a subscriber filled out the form)

    Currently the email sent to the admin gets a listing like this:
    First Name: firstname
    Last Name: lastname
    Email: email
    Event: Is always blank

    The event appears in myphpadmin for the users table

    Whats wrong with the coding in the admin emal section:
    function SendAdminIntimationOnRegComplete(&$user_rec)
    {
    if(empty($this->admin_email))
    {
    return false;
    }
    $mailer = new PHPMailer();

    $mailer->CharSet = ‘utf-8’;

    $mailer->AddAddress($this->admin_email);

    $mailer->Subject = “Registration Completed: “.$user_rec[‘firstname’].$user_rec[‘lastname’];

    $mailer->From = $this->GetFromAddress();

    $mailer->Body =”A new user confirmed (completed) their registration at “.$this->sitename.”\r\n”.
    “Event type: “.$user_rec[‘eventtype’].”\r\n”.
    “First Name: “.$user_rec[‘firstname’].”\r\n”.
    “Last Name: “.$user_rec[‘lastname’].”\r\n”.
    “Email address: “.$user_rec[’email’].”\r\n”;

    if(!$mailer->Send())
    {

  • Hi:

    I am having a hard time with registration form.
    I have been testing my work by filling out a membership registration form using my own Web site.
    The password I entered and the one in my database do not match.
    Therefore, when I fill out the log-in form, I get an error message saying that the password in incorrect.
    I would appreciate any help you are going to offer.

    • first u shud create a table for ur admin_login page and then insert username and userpassword values.Now go to login page and enter the username and password which u have inserted in admin_login page.

  • Hello Admin, please i have a problem with mysql database..each time i register a user on my website, it inserts it into the DB and works fine..here’s the problem, when i delete a particular column and try inserting a new column, instead of it to start from the previous number, it just keeps incrementing..In short, if i have a table with 5 columns, and i delete column 5,anytime i insert a new record into the database, instead of it to start from 5, it starts from 6 and so on.hope you get my question.what can be done to stop this unnecessary increment?..and i have this php code..it does not login into my db and retrieve my data..what could be wrong as well??
    Here’s the code below:

  • Nice section(?) of a login script however there are a few ways you can improve on it.

    1. You cannot just use the session_start() function whenever you want. It must be declared at the top of the page that you will be using/creating/deleting the sessions on.

    2.There is no point in trimming the password if your putting it through an MD5 hash, because only hexadecimal characters will be returned.

    3. I would strongly not advise you to use MD5 hashing without a salt. MD5 is susceptible to rainbow table attacks, and so without a salt it would make it easy to crack. Using a hash from the SHA2 family would be better altogether though.

    4. Also in your query, your selecting only the name and email(?) columns, but you need to search for the password and confirmcode columns.

  • I have been able to register a user, get the confirmation email, but when I log in I am being redirected back to a blank log in page. Any thoughts?

  • hello
    Your code is working awesome but the thing is I need my session to logout after specified amount of time of inactivity. Please provide me solution as soon as possible

  • http://www.clannersarena.com/tabbed%20panels/RegistrationForm/simfatic-RegistrationForm-dc288cf/source/register.php
    help me ASAP
    error
    Error inserting data to the table
    query:insert into fgusers3(
    name,
    email,
    username,
    password,
    confirmcode
    )
    values
    (
    “13123232”,
    “ddd@jshh.com”,
    “vfsxvsvs131313”,
    “d8e1ad19e9c8dc3f00dad57dca1cf0e5”,
    “c2880a61155b00b036b0ddd234acf9fa”
    )
    mysqlerror:Field ‘phone_number’ doesn’t have a default value
    Inserting to Database failed!

  • Very nice tutorial, many thanks for that.
    However I do have a question regarding the membersite_config file. Why is the table name included in here? Is it essential or is there another way suitable with this script? I am asking because I was wondering how I can include a forum into the script with other table names if there is one defined in the membersite_config file? Is there a way to include further tables anyway?
    Regards
    Daniel