Nov 20, 2009
Pages: 1, 2

PHP: Writing A Generic Login And Register Script

free web hosting

Read Latest Entries..: (Post #15) by Shag on Nov 7 2008, 03:44 PM.
helloi found this script on www.marakana.comI cant find how it connecnts to DBcan u guide me where exactly it is? (i think there is not any DB connection setup. it just uses users in array)and if you guys know any source where can find code which will help me to make the following….i whant to make users which can change the content of div element on the page…something like this comment box..but i whant to give this permission manualy to users and also activate there accounts manualy ...
read more.
Read the FIRST post of this Topic. - Express your Opinion! Contribute Knowledge :-).

Open Discussion & 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.

 

 

 


Comment/Reply (w/o sign-up)

coder2000
Login Tutorial

Protection Tutorial

// Reserved for error checking tutorial

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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.

Comment/Reply (w/o sign-up)

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.

 

 

 


Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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.

Comment/Reply (w/o sign-up)

Latest Entries

Shag
hello
i found this script on www.marakana.com

I cant find how it connecnts to DB
can u guide me where exactly it is? (i think there is not any DB connection setup. it just uses users in array)
and if you guys know any source where can find code which will help me to make the following….
i whant to make users which can change the content of div element on the page…
something like this comment box..
but i whant to give this permission manualy to users and also activate there accounts manualy (like on forums)and secured as much as it posible
and with registration page security i have problems as well

i am noob in php.
i dont even know if this code is secured well
if u guys can help me with this

here is the code
maybe it will help other members as well =/

File name: login.php
CODE

<?php
/////////////////////////////////////////////////////////////////////////////
//
// LOGIN PAGE
//
// Server-side:
// 1. Start a session
// 2. Clear the session
// 3. Generate a random challenge string
// 4. Save the challenge string in the session
// 5. Expose the challenge string to the page via a hidden input field
//
// Client-side:
// 1. When the completes the form and clicks on Login button
// 2. Validate the form (i.e. verify that all the fields have been filled out)
// 3. Set the hidden response field to HEX(MD5(server-generated-challenge + user-supplied-password))
// 4. Submit the form
//////////////////////////////////////////////////////////////////////////////////
session_start();
session_unset();
srand();
$challenge = "";
for ($i = 0; $i < 80; $i++) {
$challenge .= dechex(rand(0, 15));
}
$_SESSION[challenge] = $challenge;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Login</title>
&lt;script type="text/javascript" src="http://pajhome.org.uk/crypt/md5/md5.js"></script>
&lt;script type="text/javascript">
function login() {
var loginForm = document.getElementById("loginForm");
if (loginForm.username.value == "") {
alert("Please enter your user name.");
return false;
}
if (loginForm.password.value == "") {
alert("Please enter your password.");
return false;
}
var submitForm = document.getElementById("submitForm");
submitForm.username.value = loginForm.username.value;
submitForm.response.value =
hex_md5(loginForm.challenge.value+loginForm.password.value);
submitForm.submit();
}
</script>
</head>
<body>
<h1>Please Login</h1>
<form id="loginForm" action="#" method="post">
<table>
<?php if (isset($_REQUEST[error])) { ?>
<tr>
<td>Error</td>
<td style="color: red;"><?php echo $_REQUEST[error]; ?></td>
</tr>
<?php } ?>
<tr>
<td>User Name:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td> </td>
<td>
<input type="hidden" name="challenge" value="<?php echo $challenge; ?>"/>
<input type="button" name="submit" value="Login" onclick="login();"/>
</td>
</tr>
</table>
</form>
<form id="submitForm" action="authenticate.php" method="post">
<div>
<input type="hidden" name="username"/>
<input type="hidden" name="response"/>
</div>
</form>
</body>
</html>


File name: common.php
CODE

<?php
////////////////////////////////////////////////////////////////////////////////
//
// COMMON PAGE
//
// Defines require_authentication() function:
// If the user is not authenticated, forward to the login page
//
////////////////////////////////////////////////////////////////////////////////
session_start();
function is_authenticated() {
return isset($_SESSION[authenticated]); amp;amp;
$_SESSION[authenticated] == "yes";
}
function require_authentication() {
if (!is_authenticated()) {
header("Location:login.php?error=".urlencode("Not authenticated"));
exit;
}
}
?>


File Name: authenticate.php
CODE

<?php
/////////////////////////////////////////////////////////////////////////////
//
// AUTHENTICATE PAGE
//
// Server-side:
// 1. Get the challenge from the user session
// 2. Get the password for the supplied user (local lookup)
// 3. Compute expected_response = MD5(challenge+password)
// 4. If expected_response == supplied response:
// 4.1. Mark session as authenticated and forward to secret.php
// 4.2. Otherwise, authentication failed. Go back to login.php
//////////////////////////////////////////////////////////////////////////////////
$userDB = array("john" => "abc123",
"bob" => "secret",
"anna" => "passwd");
function getPasswordForUser($username) {
// get password from a simple associative array
// but this could be easily rewritten to fetch user info from a real DB
global $userDB; return $userDB[$username];
}
function validate($challenge, $response, $password) {
return md5($challenge . $password) == $response;
}
function authenticate() {
if (isset($_SESSION[challenge]) &&
isset($_REQUEST[username]) &&
isset($_REQUEST[response])) {
$password = getPasswordForUser($_REQUEST[username]);
if (validate($_SESSION[challenge], $_REQUEST[response], $password)) {
$_SESSION[authenticated] = "yes";
$_SESSION[username] = $_REQUEST[username];;
unset($_SESSION[challenge]);
} else {
header("Location:login.php?error=".urlencode("Failed authentication"));
exit;
}
} else {
header("Location:login.php?error=".urlencode("Session expired"));
exit;
}
}
session_start();
authenticate();
header("Location:secret.php");
exit();
?>


File name: secret.php
CODE

<?php
////////////////////////////////////////////////////////////////////////////////
//
// SECRET PAGE
//
// Invokes require_authentication() to ensure that the user is authenticated
//
////////////////////////////////////////////////////////////////////////////////
require("common.php");
require_authentication();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Secret Page</title>
</head>
<body>
<h1>This is a Secret Page</h1>
<p>You must have successfully authenticated since you are seeing this page.</p>
<p>
<a href="<?php echo $_SERVER[PHP_SELF]; ?>">View again?</a>
</p>
<p>
<a href="login.php">Logout?</a>
</p>
</body>
</html>

I would appreciate it
p.s sorry for english =/

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)

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

Comment/Reply (w/o sign-up)


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*

This textarea will convert to Rich-Text automatically (IE, Firefox, Chrome)

Pages: 1, 2
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) NOT NULL,   `level` int(4) default '1',   PRIMARY K....
  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(200) NOT NULL default '10....
  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',   PRIMARY KEY  (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=latin1; ....
  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
    (7)
    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 can be used to cr....
  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 &....

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

See Also,

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



PHP: Writing A Generic Login And Register Script

Affordable Web Hosting, Low cost Web Hosting - ComputingHost.com