Jump to content
xisto Community
coder2000

PHP: Writing A Generic Login And Register Script

Recommended Posts

Now there are basically 3 functions that a user management system provides: login, register, and protection. A user management system can do more than this but that is all that this tutorial will be covering. I will try to explain what I am doing as I go along but to fully understand what is happening you should have a basic knowledge of PHP, SQL, and HTML. This tutorial assumes you are using MySQL, adjust accordingly for a different DBMS.

 

First off lets define the database table where our users will be stored. Using phpMyAdmin run this statement to create our table:

CREATE TABLE tblUsers  (    fldId INT NOT NULL AUTO_INCREMENT,    fldUsername VARCHAR(40) NOT NULL,    fldPassword VARCHAR(40) NOT NULL);

Now a little explanation as to what this will do. It will create a table in your database called tblUsers with fields fldId, fldUsername, and fldPassword. The last two fields are self explanitory they contain the username and password of the user. The fldId is the user id automatically assigned by the database. For more information on the syntax read the MySQL documentation.

 

Lets continue by creating the script where our users will register. Open your favorite text editor and enter the following:

 

<?php?>

This tells the webserver that we are starting a php code section. You can have more than one in a script and you can include HTML in your code files as well, more on that later. Lets create a function that will actually do the work of adding the user to the database. Lets call it registerUser, now enter the following in between the php tags:

 

function registerUser() {    mysql_connect('server', 'username', 'password', 'database');    $username = $_POST['username'];    $password = md5($_POST['password']);    $sql = "INSERT INTO tblUsers (fldUsername, fldPassword) VALUES ($username, $password);";    mysql_query($sql);}

We now have a very basic registration function. Now we need to create the form the user will see. So below the ?> lets start our HTML. It should look a bit like this:

 

<html>    <head>        <title>Registration</title>    </head>    <body>        <form action="<?php $_SERVER['PHP_SELF']."?register=true" ?>" method="post">            Username: <input type="text" name="username">            Password: <input type="password" name="password">            <input type="submit" value="Register">        </form>    </body></html>

Now this HTML defines a form with 2 input fields and a button. The thing to look at though is the action attribute of the form tag. Here we have another php code section. This puts the path of the current script as our action with the variable register equal to true. We will deal with that in our code later. For now your code should look like this:

 

<?phpfunction registerUser() {    mysql_connect('server', 'username', 'password', 'database');    $username = $_POST['username'];    $password = md5($_POST['password']);    $sql = "INSERT INTO tblUsers (fldUsername, fldPassword) VALUES ($username, $password);";    mysql_query($sql);}?><html>    <head>        <title>Registration</title>    </head>    <body>        <form action="<?php $_SERVER['PHP_SELF']."?register=true" ?>" method="post">            Username: <input type="text" name="username">            Password: <input type="password" name="password">            <input type="submit" value="Register">        </form>    </body></html>

There is one more thing left to do. Handle the variable we passed to the script called register. Lets do that now. Here is the code:

 

<?phpif ($_GET['register'] == 'true') {    registerUser();}function registerUser() { ....

Here we use an if statement to check and see if it has been set to true if it is we call the function we defined earlier.

 

That is all I will be doing for today. Later we will go over how to login, protect your pages and some basic error checking.

Share this post


Link to post
Share on other sites

Welcome back... Today we are going to log our users into our system. For those who haven't read the first tutorial it would be a good idea to do so as this will expand on that. Now we will start on our HTML for our login form. Create a new file and call it login.php with the following:

<html>    <head>        <title>Login</title>    </head>    <body>        <form action="<? $_SERVER['PHP_SELF']."?login=true" ?>" method="POST">            Username: <input type="text" name="username"><br>            Password: <input type="password" name="password"><br>            <input type="submit" value="Login">        </form>    </body></html>
Looks familiar? It should its basically the same html as we used for our register script. Now we will start on the PHP code. To the beginning of our file add the following:
<?php    if ($_GET['login'] = true) {        loginUser();    }?><html>....
Now we are going to arrange this file a bit differently. Instead of having our function at the top of the file we are going to have it at the bottom. So lets add another PHP code block there shall we:
....</html><?php    function loginUser() {    }?>
One thing you should know is no matter how many times you open or close a PHP code block it is basically all apart of the same code. I will be demonstrating this more in a bit. For now lets just finish off our function:
function loginUser() {    $username = $_POST['username'];    $password = $_POST['password'];    $sql = "SELECT fldId, fldPassword FROM tblUsers WHERE fldUsername = '$username';";    $result = mysql_query($sql);    $row = mysql_fetch_assoc($result);    if (md5($password) = $row['fldPassword']) {        setcookie('loggedin', $row['fldId']);        echo "Logged In";    }}
One thing I should point out is that I haven't done any error checking. If you were using this in a production environment you would want to do that. In PHP you can use variables inside a string as demonstrated by our SQL statement that gets the id and password of our user. Now lets only display our form if we haven't tried to login:
if ... {} else {?><html>....</html>?>}function ...
Here we have added an else statement to our if so that if we try and login we won't be displaying our form. Notice how the closing brace for the else is in our bottom section of PHP code. Well because all PHP code in a file is parsed at the same time we can do this. Well see you next time when I show you how to protect your pages.

Share this post


Link to post
Share on other sites

After the user log in, is it better to use a cookie or opening a session, to keep checking to see if the user is logged in or not? Could you please explain why? Thanks

<{POST_SNAPBACK}>

Usually I would use a session why I didn't use it here I can't remember. I will show you in the next part how to convert it to a session so you can limit page access.

Share this post


Link to post
Share on other sites

Well its that time again. First thing we have to do is modify our login script.

function loginUser() {    session_start();    ....    if (md5(password) == $row['fldPassword']) {        $_SESSION['loggedin'] = true;        ....     }}
Now we add the session_start at the beginning of our function so that it starts our session. Now we replace our setcookie with the $_SESSION variable. Now in any other php page you want to protect just add the following code:
<?phpsession_start();if (!$_SESSION['loggedin']) {    die("Not logged in");}?>
Now there is a lot more that can be done with this but its a basic script that should get you started. Well that should be about it for this set of tutorials.

Share this post


Link to post
Share on other sites

You said this in ur register script ok :>> Now this HTML defines a form with to input fields and a button. The thing to look at though is the action attribute of the form tag. Here we have another php code section. This puts the path of the current script as our action with the variable register equal to true. We will deal with that in our code later. For now your code should look like this:ok you said that. now the part I need is the path of the current script as my action with the variable register equal to truecan you reply asap Please thanks-paul redpath

Share this post


Link to post
Share on other sites

Just leaving a message in this post so I know to come back here when I have enough time and show certain security flaws with this simple login script.Cheers,MC

Share this post


Link to post
Share on other sites

Another great login script

PHP: Writing A Generic Login And Register Script

 

There is also a great login/registration script at http://www.easykiss123.com/?p=33

 

It's a free script and there is a video that walks you through setting it up for your existing site.

 

-reply by Quantum PHP

Share this post


Link to post
Share on other sites

There are a few more things I always add to my registration code.1. Convert the username string to lowercase, strtolower(STRING), I do this so you won't get a user called User, one called user, one called USer, one called USEr, one called USER, one called uSER, and so on.. :P2. Check in the registration code if the username already exists in the database, you don't want someone to overwrite your account by simply creating a new one.- Falcon-reply by Falcon

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.