Class

Projects

  • Free MP3s on Last.fm

Sponsors

PHP / MySQL Chatroom Part 2/5 - Login Form

Printer-friendly versionPrinter-friendly versionSend to friendSend to friend

PHP / MySQL Chatroom Part 2/5 - Login Form

Setting up our site in Dreamweaver

To start let's setup our site in Dreamweaver. Because our code can only be tested on a server, you will need to have a web server or XAMPP setup on your computer to test this. Once it is we can easily have Dreamweaver copy our files over for us using the following steps:

  • Create a new folder for your chat site on your server if it doesn't exist already, this will be in C:/xampp/htdocs
  • Create a new site in Dreamweaver for our chat program select our local folder
  • Open the remote info tab, change access type to Local/Network
  • Browse your xampp/htdocs/chat folder in remote folder.
  • Check the automatically upload files on save and Dreamweaver will automatically copy your files over every time you save your file


After you save and it 'uploads' your files. You can test your program by visiting http://localhost/chat

If you make new files (images...) you may need to select your folder on the right and click the up arrow to copy everything to the server. This may help also if you notice something is still on the old server

Making sure our database tables are setup

If you don't have the info saved from the previous lesson (setting up phpmyadmin). You can create a new database called "chat", and click on the SQL tab, and insert this SQL and click submit to get the same table structute:

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) NOT NULL,
  `password` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `fname` varchar(100) NOT NULL,
  `lname` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

NOTE you will need to click the insert button and add a user into your database

Okay, so now we are ready...

Let's create a new file called index.php. This will be our main system. In the <body> of that page we will put the basic code to set how our chatroom will work:

<?php
if(!$loggedin){
//IF THEY ARE NOT LOGGED IN SHOW THIS:
?>
<p><a href="login.php">Login</a></p>
<p><a href="register.php">Register</a></p>
<p>You Must Be Logged In To Chat</p>
<?php
}else{
//IF THEY ARE LOGGED IN SHOW THIS:
?>
<p><a href="logout.php">Logout</a></p>
<p>Welcome <?php echo($user['fname']); ?>!</p>
<div id="chatroom"></div>
<form action="sendmessage.php" method="post">
    <label>Message:</label>
    <input type="text" name="message" value="" />
    <input type="submit" value="Send" />
</form>
<?php } ?>

So we start with a variable (which we have not defined yet) "$loggedin". We will later run code to check if they are logged in. If they are, the value of this will be true. If they are not, the value will be false. What we do on our index page is check that value. If the value of that variable is false (indicated by the ! symbol in the if statement), then they are not logged in so we show them a link to either login or register. If they are logged in ("}else{") we give them an option to logout as well as a form that we will have send messages to the database. There is also an empty div that will later be showing all messages.

So there are a few new pages we need to work on (login.php, register.php, sendmessage.php). Let's finish up the index page and continue.

There is going to be a lot of things going on throughout these pages, we will need to be connecting to the database over and over again. Not only that, but there will be common functions and code needed throughout the website (checking if they are logged in). We don't want to have to copy that code over and over again, so what we will do is include the same code on every page using PHP's include function. At the top of your page (Before the <!DOCTYPE>) add the following:

<?php include("inc_first.php"); ?>

What this will do is pull the code from a file called "inc_first.php", and drop it right where we inserted that include.

So this adds one more file we will need to work on since "inc_first.php" doesn't currently exist either, so with our include on our index page let's save and close the index page for now and create a new html file. Save this file as "inc_connect.php".

Our Included Files

The "inc_connect.php" file will be a simple file that will just connect to our database. If there is any HTML structure code in there select all of it and replace it so there is no code in your file except the following:

<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "chat";
//USE THE mysql_connect() FUNCTION TO CONNECT TO THE MYSQL SERVER
$dbconn = mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
//USE THE mysql_select_db() TO CONNECT TO THE DATABASE WE WANT ('chat')
mysql_select_db($dbname) or die(mysql_error());
?>

You may need to change this information depending on your servers information. We have a variable for our database host, depending on your server, this may often be "localhost" or it could be an ip address. If you are using XAMPP as your server, the data here should work fine.

The next two variables contain your database username and password which is provided to you by your hosting company (again if using xampp, the data here should work)

Last, we give a variable for the name of our  database.

We start with the mysql_connect function to connect to our database host. The function accepts parameters for the dbhost, username, and password. Then, add on an "or die(...)" function to output any errors we may run into (ie: we put the wrong username or password in).

The function after that connects to our specific database, since we may have more than one on our server, we need to tell mysql which one we want to talk to. You can then save and close this file. Currently, we haven't linked this file anywhere, we will get to that in a second.

Create another html file and get rid of any code currently inside. We will save this file as our "inc_first.php". Add the following:

<?php
//START THE SESSION
//-a session keeps track of certain values from page to page, we need to keep track of the users id# so when know they
//are logged in
session_start();
//CONNECT TO THE DATABASE
include("inc_connect.php");
//We make a variable to keep track if the user is logged in
$loggedin = false;
?>

Aside from the comments here, so far we only have three lines of code. "session_start" is a function that let's us use session variables. A session variable is saved from page to page, this will be needed to keep track of the user. The next line includes our database connect page "inc_connect.php". The last just sets the variable that we used on the index.php page ("$loggedin") to start off as false.

A quick note about including the connect page. The way this will work is our inc_first page will include all of the inc_connect.php info, so then when we include inc_first.php on our index page, it will have both the session and variable information from that page, but also our data information from the connect page. We could have included both "inc_first" and "inc_connect" from the index page instead, but this way on the rest of our pages we only need one include ("inc_first") and everything will be taken care of from there.

Login Form

So now we have our include files out of the way. Let's make another new page saved as login.php, this will be a simple html form so keep the html structure Dreamweaver gives you and in the body we can add the following form code:

<p><a href="index.php">Click here to go back</a></p>
<form action="loginprocess.php" method="post">
    <div>
        <label>Username</label>
        <input type="text" name="username" value="" />
    </div>
    <div>
        <label>Password</label>
        <input type="text" name="password" value="" />
    </div>
    <input type="submit" name="submit" value="Login" class="submit" />
</form>

A basic form that asks for a username and password. Once you click the submit button it will take you to the action attribute "loginprocess.php".  So save and close your file and we will create one more new file.

Save this as loginprocess.php (remove any html structure code from here). This file will take all of the data sent from the login form (username,password) and check with the database users table to see if the data is correct. The file will consist of the following code:

<?php
include("inc_first.php");
//PUT THE POST DATA FROM THE FORM INSIDE A VARIABLE
$username = $_POST['username'];
$password = $_POST['password'];
//CHECK IF USERNAME EXISTS
$user_query = mysql_query("SELECT id, password FROM users WHERE username = '".$username."'");
if(mysql_num_rows($user_query) > 0){
    //Set array of all user data found
    $user = mysql_fetch_array($user_query);
    //check if passwords match
    if($user['password'] == $password){
        //User info is correct, set them as logged in
        $_SESSION['user'] = $user['id'];
        //send back to the home page
        header("Location: index.php");
    }else{
        //The passwords do not match
        die("incorrect password");    
    }
}else{
    //THERE IS NO SUCH USERNAME, GIVE THE USER AN ERROR
    die("Username not found, please <a href='login.php'>go back and try again</a> or <a href='register.php'>click here to register</a>");    
}
?>

We start by including the "inc_first.php" file to make sure we can connect to the database and have any session code that we might need.

Next we put the post data in the previous login form into variables. This is optional but makes it much easier to write our code so we don't need to write the "$_POST[]" data everytime.

On the next line, we run the mysql_query function to talk to our database. The code inside the quotes is written in the MySQL language. "SELECT" tells mysql we are looking for specific data, the"id" column and the "password" column "FROM" the users table. We put a condition in the query so it is only looking for rows "WHERE" the username column is the same as the $username that the user inputted when trying to login.

When we run the mysql_query function, it will return a php resource, so we cannot directly look at any data yet. We put that resource into a variable "$users_query" so we can use the resource later in the code.

We then use the mysql_num_rows function in an if statement to check if the query found any rows with the username we checked for. If the resource does not contain any rows found, the if statement will be false and we will tell the user that the username they entered is not found. They can then either register or try logging in again.

If the username was found in the table however, we then get the data we asked for ("id", "password") and put that into an array using the mysql_fetch_array function. That function will take our resource and put the contents into the $user array. Now we can easily access our retrieved data by using $user['id'] or $user['password'].

So the username is correct, but is the password? We check to make sure that the returned table data ($user['password']) is the same as what the user entered as their password ($password). If they do not match, the user will get an error message. If it is correct, they are ready to be logged in.

We set a session variable ($_SESSION['user']) to have the same value as the users id. This is the important part, remember, this variable will be saved on every page now, so we will always know that the user is logged in, and who they are.

Finally, we sent the user back to the home page using the header function and modify the "Location".

Check Login On Every Page

We can save and close our process page, and open up "inc_first.php", we have one last thing to do. Currently we set $loggedin to false, but never check to see if they actually are logged in, add the following code below where we set $loggedin to do that:

//Detect if a user variable is set (using a SESSION)
if(isset($_SESSION['user'])){
    //If a user variable is set, lets see if we can find the user that the ID belongs to
    $user_query = mysql_query("SELECT * FROM users WHERE id = ".$_SESSION['user']);
    //If the query returned rows, let's get some information about that user, and mark them as logged in
    if(mysql_num_rows($user_query) > 0){
        //Set all user info inside this array
        $user = mysql_fetch_array($user_query);
        //Mark them as logged in
        $loggedin = true;
    }
}

The first thing we check to see here is that $_SESSION['user'] has even been set. If it hasn't, then the user has not logged in yet. If it has, then we can check to see if the id of the user exists in our database. If we can find the user in our database, we take all the information about them (saying SELECT * grabs all the columns from that row) and then put it inside an array defined as $user. Then we mark our $loggedin variable as true so we can easily check if the user is logged in or not.

When testing this out make sure you have inserted a user with your desired username and password into your users table using PHPMyAdmin.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.