PHP: Writing A Generic Login And Register Script

Pages: 1, 2
free web hosting

Read Latest Entries..: (Post #14) by iGuest on Aug 14 2008, 05:22 PM. (Line Breaks Removed)
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 a... read more.
Read the FIRST post of this Topic. - Express your Opinion! Contribute Knowledge :-).

Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > PHP

PHP: Writing A Generic Login And Register Script

coder2000
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:
CODE

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:

CODE

<?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:

CODE

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:

CODE

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

CODE

<?php
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);
}
?>

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

CODE

<?php
if ($_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.

 

 

 


Reply

coder2000
Login Tutorial

Protection Tutorial

// Reserved for error checking tutorial

Reply

jipman
Ehm m8, you might want to MD5 the passwords stored in the database...

Just a simple case of md5(password).

It's a bit more secure smile.gif


Reply

coder2000
I usually do that but missed it this time. Thanks.

Reply

-=Wrighty=-
Althoguh I already knew how to do this, thank you as I'm sure it will definitely help other users.

Reply

szupie
Do MD5(password) and password(password) do the same thing? I know they both encode them, but do they both code in MD5?

Reply

coder2000
If the password function you are refering to is the mysql function then no. Otherwise I don't know. Yes they both encrypt the password.

Reply

coder2000
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:
CODE

<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:
CODE

<?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:
CODE

....
</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:
CODE

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:
CODE

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.

 

 

 


Reply

Josh_Jpn
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

Reply

coder2000
QUOTE(Josh_Jpn @ Feb 21 2005, 04:45 AM)
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
*


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.

Reply

Latest Entries

iGuest
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.. :P

2. 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

Reply

iGuest
Another great login script
PHP: Writing A Generic Login And Register Script

There is also a great login/registration script at 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

Reply

mastercomputers
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

Reply

iGuest
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 true

can you reply asap Please thanks

-paul redpath

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.
Confirm Code:

Pages: 1, 2
Recent Queries:-
  1. register register script with validation - 0.71 hr back. (1)
  2. how to avoid same username register php codes - 5.34 hr back. (1)
  3. html register script - 5.73 hr back. (1)
  4. php mysql simple login register - 6.92 hr back. (1)
  5. php login register - 7.48 hr back. (1)
  6. html login and register script - 8.95 hr back. (1)
  7. register php script - 8.57 hr back. (2)
  8. registration and login php sql - 15.01 hr back. (1)
  9. php login mit register - 21.23 hr back. (1)
  10. secure login register script - 21.33 hr back. (1)
  11. login register script - 21.35 hr back. (1)
  12. basic php register script - 22.17 hr back. (1)
  13. login registration scriot - 23.04 hr back. (3)
  14. html script for register - 24.74 hr back. (1)
Similar Topics

Keywords : writing, generic, login, register, script

  1. Creating A Php Login Script
    A thorough look at the process behind it (3)
  2. A Simple Register Script
    This Is a Very Simple Register-Script (3)
    Some time ago, i made a login-script. But how do you use a login-script, if you can't register.
    So this morning, I decided to make a register-script.. What you should already know: The php
    basics and a little more. How to use php and mysql together. The HTML basics (to make the forms).
    The first thing we should do, is creating the database tables. Here is the code: CODE CREATE
    TABLE `user` (   `id` int(4) unsigned NOT NULL auto_increment,
      `username` varchar(32) NOT NULL,   `password` varchar(32)....
  3. Attack Script In Php
    This is a funny attack script that i made (5)
    Hey! I am going to share an attack script that i made for some time ago. I made it, as a test
    for my game.. And ofc, you can use it for your game to. It is still version 1.0. But I want you to
    learn something from it /wink.gif" style="vertical-align:middle" emoid=";)" border="0"
    alt="wink.gif" /> This is my second tutorial here, and I will try to make it better than my first
    one /smile.gif" style="vertical-align:middle" emoid=":)" border="0" alt="smile.gif" /> Here is
    the SQL File. CODE CREATE TABLE `characterss` (   `health` int(2....
  4. Very Simple Login-script
    This is a very simple and secure login-script (18)
    Hi. This is my first post here. please Tell me if i do something wrong. This is a very simple and
    secure login script. I will try to add as many comments as possible, to make it easier to
    understand. Lets start with the database. Just make a new SQL file, and call it whatever you want.
    Paste this code: CODE CREATE TABLE `user` (   `id` int(4) unsigned
    NOT NULL auto_increment,   `username` varchar(32) NOT NULL,   `password`
    varchar(32) NOT NULL,   `level` int(4) default '1',   PRIM....
  5. Writing Functions In PHP
    Turn Your PHP Script Into A Reusable PHP Function (6)
    Well, it has been a while since I offered a tutorial here at AstaHost. Most of my creativity has
    gone toward my new website, Handy PHP . The website is just getting started and it is hard to post
    potential content for my website here instead of there. The purpose of this tutorial is to show you
    how to convert a standard PHP script into a reusable PHP function. It is funny, because this
    tutorial is very similar in nature to the very first tutorial I wrote here. Rapid HTML code
    generation using simple PHP would be a good topic to read with this tutorial. Before we....
  6. Simple User Validation Script
    (5)
    This tutorial will show you how to create a simple user validation script with PHP. We will need
    two files: "protect.php" and "login.php". The protect file is not meant to be viewed by itself. In
    order to protect a page, you need to include that file by using PHP code like the following: CODE
    include("protect.php"); Keep in mind that this needs to be in between your
    tags. This bit of code uses the include function. It is a handy function that reads all the
    information contained in one file and temporarily adds it to another. For example, this c....
  7. PHP Tutorial: Form Verification And Simple Validation
    A One Page script for PHP form verification. (12)
    Having used various means of verifying HTML forms I believe that this method of verifying a form
    to be the best mostly because it does everything on one page. It presents the form on one page and
    then when the submit button is pressed, if all the required fields are not filled out then it will
    present the form again with all the fields intact and in red lettering will point out the fields
    that are required to be filled out in red. It is not possible to click submit using this method even
    if the user has turned JavaScript off. While it is possible to use javascript to ....
  8. PHP Tutorial: Menu Or Sidebar Script For CMS101
    and other applications as well (6)
    A Php Menu-builder Tutorial This Sidebar Menu-builder code and the php scripts are adapted from
    a Tutorial on the Astahost.com Forum titled : CMS101 - Content Management System Design .
    Since the original tutorial's author (vujsa) did such a marvellous job of describing the system
    in the original Topic posting, I will not attempt to explain it here, rather, I invite you to have a
    look at his Topic and learn from it. The Basic tutorial provided coding for developing a table-based
    web-site template which used php includes and embedded data to create a &....
  9. Creating Your Own Image Gallery With Php
    A Guideline, Not A Complete Script (3)
    Recently a member asked how to create a photo gallery using his various directories filled with
    image files. Here is an overview of the steps and fuctions needed to do this. Assuming that the
    following directories exists and are full of image files: www.testsite.web/photos/gallery1/
    www.testsite.web/photos/gallery2/ www.testsite.web/pictures/album1/ In order to get the contents
    for a specific gallery you'll need to let the script know which one to look in. You'll need
    to use a link that carries the arguments needed to locate the right photos. www.testsite.we....

    1. Looking for writing, generic, login, register, script

Searching Video's for writing, generic, login, register, script
advertisement




PHP: Writing A Generic Login And Register Script



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute more info. to help others.
Ask your Doubts & Queries to get answers, So that "Together We can help others!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE