WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1]
SELECT rating_username, rating_rating, rating_ip FROM wp_ratings WHERE rating_postid =

The frontend form and the PHP user login validation script

Vote This Post DownVote This Post Up (-1 rating, 3 votes)
Loading ... Loading ...

PHP & MySQL Login Tutorial Series
Pt1: Introduction
Pt2: Setting up the database
Pt3: The front end and user validation
Pt4: The code to privatize a page
Pt5: Logout function and clearing the session ID

Part 3: Frontend form and validation

In this example we’re going to have a simple page that will display username and password text fields if a user is not logged in, and a simple greeting if the user is logged in. The HTML form code for the user/pass login should look something like this:

<form action=”sample.php” method=”POST”>
<input type=text name=username>
<input type=password name=password>
<input type=submit value=”Log In”>
</form>

This HTML will give us a simple form with two fields named username and password. When a user enters the login info and clicks the submit button, the page will reload. Now we need to add in the PHP to retrieve these credentials when the page is loaded. To make sure everything works, add all of the PHP code to the top of the document (as seen in sample.php). To simplify the tutorial we’re going to give you the code for logging in, logging out, and checking user status in one snippet, however we will not be discussing all of it just yet. Here is the code that will regulate the user activity:

<?php
if($_POST[username] !=” || $_POST[password] != ”) {
$login_status = login($_POST[username], $_POST[password]);
} else if($_GET[logout]) {
logout();
}
$userid = status();
?>

Note: The above code must appear before any output in your document. If there is ANY output prior to this code being executed, you will receive errors when cookies are trying to be set during login.

We first check to see if the user is logging in, in which case we’ll call the login function, and we’ll also check to see if they’re logging out, in which case we will log out the current account. Finally we check to see the user’s status. If the user is logged in the userid will equal the user id. Otherwise it is equal to 0. Now let’s look at the functions we call in the above code.

The first function we’ll check is the login function. This is the meat of the program that will check user credentials. The code looks like this:

<?php
function login($username, $password) {
$username = addslashes($username);
$password = md5($password);
$query = mysql_query(”SELECT * FROM user_accounts WHERE username=’$username’ AND password=’$password’”);
if(mysql_num_rows($query) == 1) {
$info = mysql_fetch_array($query);
$userid = $info[userid];
$sessionid = md5($userid . time());
$time = time();
@setcookie (’test_account’, $sessionid, $time+3600, ‘/’, ”);
mysql_query(”DELETE FROM user_sessions WHERE userid=’$userid’”);
mysql_query(”INSERT INTO user_sessions (sessionid,userid,timestamp) VALUES(’$sessionid’,'$userid’,'$time’)”);
return $userid;
} else {
return 0;
}
}
?>

We begin by reading in the username and password. We used addslashes() to help protect against SQL injection attacks. Generally you wouldn’t have single quotes in usernames, however if someone tries to break into the system this will help protect you. Next we encrypt the password with MD5. MD5 is a hashing algorithm that will scramble any text and return a 32-character string. Whenever you add a user to the database, make sure the password is saved as a 32-character MD5 string. This will guarantee that anyone who may break into your database will not be able to steal your users’ passwords. Again while this is not foolproof, it does help protect user data. The idea is that instead of matching two visible passwords, it’s better to match a scrambled password with the real password’s scrambled counterpart. Since MD5 will always return the same 32-character string for a specific input, we can guarantee that the MD5 hash stored in the database will always match the MD5 hash of the correct password. If you do not wish to encrypt your passwords, simply remove this line from the login function.

We then check the database to see if a user exists with the entered username/password combo. If a user does not exist we’ll return the integer 0. This is arbitrary, however the number must remain consistent throughout your program. If the user does exist, we’ll fetch the user id number. We then create a session id (again with md5). Note that we’re not only encrypting the user id as the session id, but we’re also concatenating the current timestamp to the user id. This will make it near-impossible for a would-be hacker to guess an active session id. You can use other salts to protect the session id even more.

After we have our session id we will want to store it on the user’s computer. To do this we call the setcookie() function. The first parameter, “test_account,” is simply the name of the cookie. Again you can set this to be whatever you want, however it must remain consistent throughout your code. The second parameter is our cookie contents, in this case the session id. It’s important that we only store non-identifiable information in the cookie. If we were to store something such as the user id or a username, it would be very easy for the would-be hacker to spoof the cookie and gain access to your user accounts. By using a session id, the hacker has to know the id in order to spoof; with our MD5 encryption this becomes difficult and makes it harder for the hacker to exploit your script. The third parameter is the cookie expiration time. $time+3600 is the current time plus 3600 seconds, or one hour in the future. Finally we set the directory the cookie is valid for. It’s sufficient to leave this parameter set to “/”.

After we set the cookie we need to clear out the session table. First we will want to wipe any old sessions for our user. We then insert the new session so we have something to match the cookie against whenever the user returns to our site.

Next -> Privatizing a page on your website

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Webnews
  • MisterWong
  • Y!GG

One Response to “The frontend form and the PHP user login validation script”

  1. Its a good tutorial, for some reason i cant get it to work though. I must be doing something wrong

    here is the page I have it on
    http://www.arcube.com/sample.php

    what am i doing wrong

Leave a Reply

You can use these XHTML tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>