Nov 20, 2009

Simple User Validation Script

free web hosting
Open Discussion & Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > PHP

Simple User Validation Script

bluefish
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 <?php and ?> 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 create an easily modifiable template. You don’t really need to know exactly how it works to use it, though.

The login page is where users will enter their username and password in order to log in to your website. We’ll start by working on the login.php file.
CODE
<form action=login.php method=post>
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>

That is a bit of HTML that will create a login form, with two fields: username and password. When your users click the submit button, the page will reload (because we specified login.php as the action for the form – the action is the place the information contained will be sent to). When the page reloads, however, we want to see the post data – the information the user has sent, so that we can check if it is valid. To do that, we can use a bit of PHP code at the beginning of the page like the following:
CODE
<?php
if(isset($_POST["username"])&&isset($_POST["password"])) {
echo "Thank you for trying to login.";
}
?>

If you put that code at the top of your login.php page, you’ll notice that when you press submit it will show the text. The "if" statement that I used may look new to you. The isset function checks if the given variable exists. The $_POST array indexes all the information that has been posted to the page. So when we use $_POST["username"], we are getting the posted value of the input indexed as "username" (as determined by the name parameter of our "input" fields that I showed you earlier). When combined with isset, we can check whether the user has posted a value to the page.

Now, we need to check if the user has entered correct information. To do so, we can use PHP code like the following (in place of the echo command in the above code).
CODE
$user = $_POST["username"];
$pass = $_POST["password"];
$validated = false;
//Begin validation code
if($user=="User1"&&$pass=="password1") $validated = true;
if($user=="User2"&&$pass=="password2") $validated = true;
//End validation code
//Begin login code
if($validated)
echo "Logged in as $user.";
else
echo "Invalid username/password combination.";
//End login code

This is a rather simple way to check. If we have more users, we could use something like the following in place of the validation code above:
CODE
$passwords = array("User1"=>"password1", "User2"=>"password2");
if(isset($passwords[$user])) if($passwords[$user]==$pass) $validated = true;

That code puts the passwords into an associative array, then checks to see if the password for the user is correct. Which method you choose does not matter.

Now, of course, we need to actually do something when we log in. To do this, we will use cookies. Cookies are pieces of data that websites can store on users’ computers. We will need to store login information. Each website has its own cookie, so we don’t need to worry about having the same names as other websites.
To set a cookie, we use the setcookie function. One important note about the setcookie function: you must use it before any statements that print data, e.g. echo.
CODE
//Begin login code
if($validated) {
setcookie("username", $user); //Sets a cookie storing the username
setcookie("password", MD5($pass)); //Sets a cookie storing the encrypted value of the password
echo "Logged in as $user.";
} else {
echo "Invalid username/password combination.";
}
//End login code

Now, one thing you may be confused about is the MD5 function. The MD5 function encrypts data. This is a simple security measure, and is by no means foolproof, but it helps protect you. I’ll show you later how to use the MD5 function to check if the password is correct.

We’re done with the login.php page. It should now correctly log you in. Here is the full code:
CODE
<?php
if(isset($_POST["username"])&&isset($_POST["password"])) {
$user = $_POST["username"];
$pass = $_POST["password"];
$validated = false;
//Begin validation code
if($user=="User1"&&$pass=="password1") $validated = true;
if($user=="User2"&&$pass=="password2") $validated = true;
//End validation code
//Begin login code
if($validated) {
setcookie("username", $user); //Sets a cookie storing the username
setcookie("password", MD5($pass)); //Sets a cookie storing the encrypted value of the password
echo "Logged in as $user.";
} else {
echo "Invalid username/password combination.";
}
//End login code
}
?>
<form action=login.php method=post>
Username: <input type="text" name="username"><br>
Password: <input type="password" name="password"><br>
<input type="submit" value="Login">
</form>


Now, we need to edit the protect.php page.
We’ll use a similar method for the login.php page to check if the user is logged in correctly.
CODE
<?php
$validated = false;

//Use $_COOKIE to get the cookie data – same usage as $_POST
if(isset($_COOKIE["username"])&&isset($_COOKIE["password"])) {

$user = $_COOKIE["username"];
$pass = $_COOKIE["password"];

//Begin validation code
if($user=="User1"&&$pass==MD5("password1")) $validated = true;
if($user=="User2"&&$pass==MD5("password2")) $validated = true;
//End validation code
}

if($validated) {
//Ok; don’t need to do anything
} else {
//Make user go to login page
header("Location: login.php");
exit;
}
?>

The above code should look very familiar to you. It is basically the same as the login script, except for a few key differeneces:
First, $validated has moved outside of the block of code. This is because as opposed to only doing something when they post, we need to protect our page all the time.
Second, we use $_COOKIE instead of $_POST. This is because we want to get the cookie data. Nothing has been posted to the page, so $_POST is useless.
Third, we use MD5 to encrypt our set password before comparing it to the stored password. This is because the stored password is already encrypted and by encrypting the other before comparing we make sure the comparison is fair. We can't decrypt the stored password because MD5 is one-way encryption. But don't worry about encryption – just make sure when you are comparing two values either both or neither of them should be encrypted for it to work properly.
Fourth, the actions have changed. We no longer do anything when we have been validated, but if we haven’t been validated, we use the header function. This is a complex function. All you need to know for now is that header("Location: page"); redirects the user to the given page. We want our users to be redirected to the login page if they are not allowed to access the page. Then, we need to exit the script because we are done with the page.

Great! Now we have a working user validation script. Remember to include protect.php whenever you want to protect a page. This is only a simple script, though. There are many ways to improve it, such as:
-use a MySQL database for users
-automatically redirect back to the page the user came from when they log in
-have an access level specifier that allows certain users access to certain pages
-allow easy creation of users

If you have any questions or comments, or if you notice a problem with my tutorial or code, please reply. Feel free to ask me for details if you want to extend your code using one of my suggestions.

 

 

 


Comment/Reply (w/o sign-up)

Network
i like it, there is just one thing, sometimes a server can go wrong with files, it doesnt happen very often, but can happen, now if for some reason it cannot find protect.php it will just display an error and execute the rest.

require() instead of includes() is probably better used here, so that the script will stop if it cannot find protect.php

but other than that, i think your tutorial is excellent, by far better than some i have seen, 10/10 for explanation and clarity

Comment/Reply (w/o sign-up)

wutske
personaly, I would work with session variables, they are more secure than cookies. I've once made a little script to log-in using session variables, I'll look it up when I have some spare time smile.gif .

Comment/Reply (w/o sign-up)

Mordent
Hmmm...well, it looks like I'm branching out towards making my own little gaming community site, and I'm curious about the difference in levels of security. For example, if I use sessions instead of cookies, and they're more secure, why would anyone want to ever use cookies? Correct me if I'm wrong, but cookies allow someone to "retain" data for however long it takes for the cookie to expire, whereas sessions only last until you close the browser window (or the like)?

If so, I'd have to admit I agree with wutske, but that's just my personal preference. *shrugs*

Before I forget to mention, including a nice little user database idea might not be a bad one. I'm currently toying with automatic email validation, and it's going pretty well. As a relatively experienced programmer (in general), making the move to PHP wasn't overly difficult. I'm still not a fan of the complications involved in getting the site to look nice while working fully (as echo just doesn't feel right for putting in large chunks of XHTML code, but maybe that's just me). How do you folks get around that problem?

 

 

 


Comment/Reply (w/o sign-up)

Network
QUOTE(Mordent @ Nov 8 2007, 05:39 PM) *
Hmmm...well, it looks like I'm branching out towards making my own little gaming community site, and I'm curious about the difference in levels of security. For example, if I use sessions instead of cookies, and they're more secure, why would anyone want to ever use cookies? Correct me if I'm wrong, but cookies allow someone to "retain" data for however long it takes for the cookie to expire, whereas sessions only last until you close the browser window (or the like)?

If so, I'd have to admit I agree with wutske, but that's just my personal preference. *shrugs*

Before I forget to mention, including a nice little user database idea might not be a bad one. I'm currently toying with automatic email validation, and it's going pretty well. As a relatively experienced programmer (in general), making the move to PHP wasn't overly difficult. I'm still not a fan of the complications involved in getting the site to look nice while working fully (as echo just doesn't feel right for putting in large chunks of XHTML code, but maybe that's just me). How do you folks get around that problem?


Now this may help, may not, but when i first created a community i found it useful to look at some professional open-source portals and CMS's before i started an example is Joomla, but there are loads more

Comment/Reply (w/o sign-up)

comkidwizzer3
When using this PHP script for the login where does it search for registered users. I have already made a register and login form which comply with my database.

Comment/Reply (w/o sign-up)

(G)Raj Sadagopan
ser to a specific page based on the username and password they enter in joomla
Simple User Validation Script

I am building a website based on Joomla and it has already a login page. It also has a login redirect built in but that only redirects to a group. I want to introduce a php script that will authenticate the user and will redirect individual users to specific application url residing on the localhost.. At the moment I created page on the website for client login and it redirects the group to one specific application. I have different applications on the server and I need the user name and password to be authenticated and the client to be redirected a specific application url meant for him. Can you please help me. I am not a programmer.

I can send you the login.Php and any related scripts.

Thanks for your kind understanding assistance.

Raj


Comment/Reply (w/o sign-up)

HannahI
Nice tutorial you made smile.gif

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)

Similar Topics

Keywords : simple, user, validation, script

  1. How To: Display A Members/user List.
    With PHP, Mysql, and HTML. (4)
  2. Creating A Php Login Script
    A thorough look at the process behind it (3)
    Hey all, after reading through a fair number of tutorials on this subject I decided to write a
    pretty detailed one myself. Apologies for those who don't like my structured layout, it's
    just the way I do things. /wink.gif" style="vertical-align:middle" emoid=";)" border="0"
    alt="wink.gif" /> Title: Creating a PHP Login Script Objective: To go through a series of basic
    steps required to create a method of user registration, login and permission management using PHP
    and MySQL. Notes: The information is designed to work fully on AstaHost's hosting plans. ....
  3. How To Create A "user Profile" Page.
    No design (easy to add later if you want). (22)
    Hi! It was a long time ago I created a tutorial, so I've decided to create a new one
    /wink.gif" style="vertical-align:middle" emoid=";)" border="0" alt="wink.gif" /> This time, I am
    going to teach you, how to create a "user profile page". Lets say I am logged in on my account, and
    want to view someone else account information (in this case, only his username, but you can add more
    things later). Then I'll press on a link, that will take me to his user profile. But before
    you can do that, you will have to create a register script, and a login script. If you d....
  4. 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....
  5. 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....
  6. 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; ....
  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. PHP: Writing A Generic Login And Register Script
    (15)
    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....

    1. Looking for simple, user, validation, script

See Also,

*SIMILAR VIDEOS*
Searching Video's for simple, user, validation, script
advertisement



Simple User Validation Script

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