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:
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 >
<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' />


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()
        $this->HandleError("UserName is empty!");
        return false;
        $this->HandleError("Password is empty!");
        return false;
    $username = trim($_POST['username']);
    $password = trim($_POST['password']);
        return false;
    $_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)
        $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:



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

Here is the CheckLogin() function code.

function CheckLogin()

     $sessionvar = $this->GetLoginSessionVar();
        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.


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


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

Comments on this entry are closed.

  • hi,
    I am trying to do a lost password feature.  Is there any pointers to how I can retrieve the password encrypted in md5 digest? meaning, how do i undigest the password and send it back to the user?
    Thanks for your help

    • md5(), by definition, can’t be reversed. You have to generate a new password and send it

    • This is a very good point I have been trying to search the internet for a solution to this
      The only answers out there are md5(), by definition, can€™t be reversed. You have to generate a new password and send it.
      But does anyone now how to auto generate a new password and have it sent to the user?
      many thanks


  • This is a slick collection of code. Thanks.
    I have a problem with the authorization. If I move these pages into sub folders off the server root this routine fails.
    This error “Call to a member function CheckLogin() on a non-object in … ”
    I thought it was because the include statement is no longer correct, so I fixed that. But still the actual check of the user status fails. Leaving me with a blank page.
    I’d also like to use some of the functions you defined, specifically the variables defined for access to the database, that way I don’t have to define them in my own routine.
    “Include this sample piece of code on top of your protected pages:








    • Thanks for this piece of code.
      I tried to use them, everything works fine to some point. The problem am facing right now is to have access to login-home.php page. When I log in, it doesn’t redirect login-home.php instead it lands to login.php page.
      I have tried with session settup on top of the page, the it shows up 0 at the far left corner of the browser.
      Is any one have spare time to shed a light on this please!
      I will appreciate your help.

    • I am having the same issue. Has this question been answered?

  • ok so everything works great excepet for two things first is this set of scripts encrypts md5 into lower case and if you use navicat it doesnt recognize it unless its caps .
    second is this
    Failed sending registration confirmation email

    • heya dude….im also having the same problm “failed sending registration confirmation email” … did you solved yours…. thnks in advnce 🙂

  • do we nid to change some part in the phpmailer in order for it to send email….i did change only the membersite_config, and the fg_membersite ….just the emailing to the member part is not working…..thnks in advance

  • Excuse me, what do you put into fg_membersite.php so that I get E-Mailed their password when they register?

    • I lied there may be an easier way to do it, through the $formvars[‘password’] into a variable (I think only variable will work because a form and class both store variable and information but will release it if escaped outside of code like in an else } statement which the email is and I think the variable method will take the information and store it even outside of an else } statement remember it does not need to even say else to make it an else statement it could be something as simple as function reads here { and sometimes here } function does not read here so basically $emailpassword = $formvars[‘password’]; put that before the email and then somewhere in the email and I think it may work. I have not tested at all just kind of popped into mind, but once again you should not violate a users privacy.

      • oh yeah once again I forgot this blog deletes php code, plus does not let you make edits, where I stated “form and class” I meant function and class and I forgot to close my open thought with a ‘)’ anyways the section to put somewhere in the email is “open php tag” echo $emailpassword; “close php tag” the reason I think this will work is because it gathers the data from the functions via $formvars and stores it then can re-render after function and $formvars are ended.

  • for this registration form I need to randomly generate a password and send a mail automatically as he registers, with his email id as username and randomly generated password.Pls suggest.

    • @Sushma – Just add “Password: “.$formvars[‘password’].”\r\n”. after “Username: “.$formvars[‘username’].”\r\n”. under $mailer->Body in the file include/fg_membersite.php near line: 406 ; make sure you include the ” and the . otherwise you will end up with a syntax error.

  • Hello,
    I was looking to possibly get help from either creator or anyone, I added a few fields and all fields are being recorded into the database properly and having no issues there, the problem is that I can’t get a confirmation code; let me rephrase I get an email as supposed to it contains a link, I go to that link and it says wrong confirmation code even if I strip it from url and past in box still the same and have even copied directly from database. Anyone feeling up to helping? I can possibly make this easier, I am 100% sure I don’t even need this feature if it is easy to remove.

  • Actually scratch what I last posted, I have resolved it. However I still have a question, in a basic form if you wanted to add a drop list option you would just do something like this SaleNot InterestedFollow Up

    how would I save the answer to this in a database with this particular form. Also if I call all of the database tables to editable fields by inserting value of each input to the table quarry results how do I update all fields at once even if no changes are made.

  • This is what I have

    CID: <input type="text" value="”>

    First Name: <input type="text" value="”>

    Company: <input type="text" value="”>

    Address: <input type="text" value="”>

    Phone: <input type="text" value="”>

    Mobile: <input type="text" value=" “>

    Email: <input type="text" value="”>

    Status: <input type="text" value="”>

    Assigned Agent:

    to pull results from the database based on username entered into the form, however I get the messages

    Warning: mysql_query() [function.mysql-query]: Access denied for user ‘millcre1’@’localhost’ (using password: NO) in /home/millcre1/public_html/ on line 112

    Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/millcre1/public_html/ on line 112

    Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/millcre1/public_html/ on line 113

    how do I resolve? I know it needs to connect the and login to the database similar to how the form does to register but how do I make it connect?

    • grr I just relized it wont let me post php script into the message….I really hope the creator can contact me but I know this is just a hope no creator ever has the time to actually help.

  • The registration form works very good thanks but the login form doesn’t work. When I insert my data it always answers: “Error logging in. The username or password does not match”. Someone has had the same problem? How can I solve it? Thanks

  • Thanks for the codes

  • This might be a dumb question–and this is a great tutorial BTW–but where in the code does it communicate with my database? Or does it? Any suggestions on a free database to store my usernames/pws? ie. MySQL or Open Office? Thanks for any advice–end of line.

    • mysql is most popular next to msaccess and postgresql, you have a lot of learning to do, begin with understanding how a database works and then start learning basic php then everything will start logically coming together for you.

  • Hi, thanks for the tutorial.
    I am getting error at start of the registration
    Error : “Failed to select database: testdb Please make sure that the database name provided is correct mysqlerror:Access denied for user ”@’localhost’ to database ‘testdb’
    Database login failed!”

    I already follwed the instructions of Read me. I tried with/without username and password for database.

    • You have to provide your database login details and your database name.

  • Thank you very much for the code. everything works fine. The only thing i need to do is to set-up the forgot password link, just in case someone forget their password.
    Please help i have no clue on how i can do this. Thank you.

    • You can not do this with MD5 without setting up another table and creating both md5 and plain text but only reading the md5. The easiest method would be to do similar to as I told Sushma which is the following ” @Sushma €“ Just add €œPassword: €œ.$formvars[‘password’].€\r\n€. after €œUsername: €œ.$formvars[‘username’].€\r\n€. under $mailer->Body in the file include/fg_membersite.php near line: 406 ; make sure you include the € and the . otherwise you will end up with a syntax error.”
      Then just explain it is up to them to save this email with their password in it.

  • Hey, I keep getting the “Failed sending registration confirmation email.” My db is set up and everything is posting fine but I am stuck. Any help? Where do I configure my smtp settings? Do I need to add files to this bundle or can I just configure everything here? What file is the smtp info in?

  • hi, i have a little problem, for example, on this line

    Welcome back UserFullName();?>!

    i see rthe message on the page

    Welcome back UserFullName();?>!

    the name is missing, it only appears the function can u help me!? 🙂

  • help ful

  • do i need to open my xampp to run this program?

  • Fantastic code and tutorial.

    What code, specifically, can be used to retrieve and display a registered user’s data input?

    More specifically, a user (after successfully logging-in) will be presented with a form. The form input needs to be stored in the user’s record file, and made available for review immediately and following a successful login.

    Hope to hear back soon.

    Many thanks and Happy New Year! (2012)

  • I like it