Jump to content
xisto Community
Sign in to follow this  
bluefish1405241537

Simple User Validation Script

Recommended Posts

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:

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.

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

<?phpif(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).

$user = $_POST["username"];$pass = $_POST["password"];$validated = false;//Begin validation codeif($user=="User1"&&$pass=="password1") $validated = true;if($user=="User2"&&$pass=="password2") $validated = true;//End validation code//Begin login codeif($validated)echo "Logged in as $user.";elseecho "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:

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

//Begin login codeif($validated) {setcookie("username", $user); //Sets a cookie storing the usernamesetcookie("password", MD5($pass)); //Sets a cookie storing the encrypted value of the passwordecho "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:

<?phpif(isset($_POST["username"])&&isset($_POST["password"])) {$user = $_POST["username"];$pass = $_POST["password"];$validated = false;//Begin validation codeif($user=="User1"&&$pass=="password1") $validated = true;if($user=="User2"&&$pass=="password2") $validated = true;//End validation code//Begin login codeif($validated) {setcookie("username", $user); //Sets a cookie storing the usernamesetcookie("password", MD5($pass)); //Sets a cookie storing the encrypted value of the passwordecho "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.

<?php$validated = false;//Use $_COOKIE to get the cookie data â same usage as $_POSTif(isset($_COOKIE["username"])&&isset($_COOKIE["password"])) {$user = $_COOKIE["username"];$pass = $_COOKIE["password"];//Begin validation codeif($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 pageheader("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.

Share this post


Link to post
Share on other sites

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.phpbut other than that, i think your tutorial is excellent, by far better than some i have seen, 10/10 for explanation and clarity

Share this post


Link to post
Share on other sites

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 ;) .

Share this post


Link to post
Share on other sites

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?

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
ser to a specific page based on the username and password they enter in joomlaSimple 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

Share this post


Link to post
Share on other sites
same problem as Raj SadagopanSimple User Validation Script

Am a student of IT, developing a site using joomla but facing almost the same problem as Rag Sadagopan. I need to redirect individuals to specific pages when they login. Apparently they all view the same content when they login. I need some help.

thanks

Share this post


Link to post
Share on other sites
HELP please???.Simple User Validation Script

Hi, I have a question if you don't mind please??? I have already my registeration form and all! but I actually don't know how to make it like when pressing "Sign Up", it stores my users info on MySQL???? AND also how can I make my page like when someone goes to my page, the person would go to a main page with login with sign up form underneat and not be able to see anything until logged in or signed up? THANKS!

 

Share this post


Link to post
Share on other sites

Hi,Nice post. I'am new to this. I need a login page which will redirect visitor to different pages depending on the username and password. can you pls help me with the code?My website is subdomain of weebly. will php codes work in weebly subsites??

Edited by yordan
Do not post your private mail address on a public forum.... (see edit history)

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
Sign in to follow this  

×
×
  • 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.