Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> Simple Password Protect With Cookies [php], Beginner
Rating 4 V
Adrian
post May 3 2006, 08:38 AM
Post #1


Addicted Dot
Group Icon
Group: Moderator
Posts: 7,028
Joined: 26-September 04
Member No.: 763





Simple Password Protect with Cookies


By Adrian
About this time I made a very simple password protection script tutorial (here) and since then everyone (including myself) has realized this really is a very simple password protect script and since about August last year I promised to do a slightly more advanced user system, well finally I am going to do it.

What's different this time?
Well this script is alot more flexible, its more secure, and its much easier to add it to multiple pages.

What doesn't it have?
Well just so you don't get confused this is really designed for Admin panels. It doesn't include anyway of registering, there isn't support for multiple users and it isn't run from any kind of database it is just a plain and simple password protection script purely for admin panels.

config.php
Lets get started. First we're going to write the config file. I wont explain this because it is simply defining variables but if you read the comments and the variables in it you should get the idea of it. Save the below as config.php:
CODE
<?php
//Admin Username and password
$adminuser = "demo";
$adminpass = "demo";

//Error message variables
$not_logged_in_message_error_message = "Error... Error... You Are not logged in. Go back and try again!<br>";
$incorrect_error_message = "You have entered the incorrect Username and/or Password, please go back and try again!<br>";
$no_pass_or_user_error_message = "You have either not entered a password or a username, please go back and try again!<br>";

//The first page you want the script to go to after creating those cookies (this page must include the validating code as seen in admin1.php)
$first_page = "admin1.php";
?>

All you need to change above is the $adminuser and $adminpass (Admin Username and Password respectively) and if you want you can change the error messages.

index.php
We need a form for the user to enter the username and password details. There is no PHP in this but I have saved it as a .php file to keep all my file extensions uniform. If you change the extension to .html remember to edit the logout file (below) accordingly because that forwards to this page. Save the below as index.php:
CODE
<html>
<head>
<title>Login Page</title>
</head>
<body>

<table width="400" border="0" align="center" cellpadding="3" cellspacing="00">
  <tr>
    <td><strong>Login Form </strong></td>
  </tr>
  <tr>
    <td><form id="form1" name="form1" method="post" action="login.php"><table width="100%" border="0" cellspacing="00" cellpadding="3">
      <tr>
        <td width="49%"><div align="right">Username:</div></td>
        <td width="51%"><input name="formuser" type="text" id="formuser" /></td>
      </tr>
      <tr>
        <td><div align="right">Password:</div></td>
        <td><input name="formpass" type="password" id="formpass" /></td>
      </tr>
      <tr>
        <td> </td>
        <td>
          <input type="submit" name="Submit" value="Login!" />        </td>
      </tr>
    </table>
    </form></td>
  </tr>
</table>
</body>
</html>


login.php
This is the page which the above login form sends the information to. This form takes that information, stores it in some cookies and forwards to the main admin page (admin1.php, see below). Save the below as login.php:
CODE
<?php
$formuser = $_POST["formuser"];
$formpass = $_POST["formpass"];
$formpass = md5($formpass);
if($formuser && $formpass) {
    setcookie ("cookuser");  
    setcookie ("cookpass");
    
    setcookie ("cookuser", $formuser);
    setcookie ("cookpass", $formpass);
    header("Location: admin1.php");
    }
    else {
        include("config.php");
    echo($no_pass_or_user_error_message);
    }
?>

Ok, now to explain all that.
CODE
$formuser = $_POST["formuser"];
$formpass = $_POST["formpass"];
$formpass = md5($formpass);

The first 2 lines put the username and password entered on the login form into their own variables. The 3rd line takes the password and converts it to an md5 hash for added security.

CODE
if($formuser && $formpass) {
    setcookie ("cookuser");  
    setcookie ("cookpass");
    
    setcookie ("cookuser", $formuser);
    setcookie ("cookpass", $formpass);
    header("Location: admin1.php");
    }

First Line: If $formuser and $formpass are in existance with a value then do the following:
Next 2 lines: these make sure that there is no cookie in existance on the users computer with the names cookuser and cookpass by deleting them.
Lines 5 & 6: These make a cookie for the username and a cookie for the password and store the information from the form in them.
Line 7: This forwards the page to the main admin page (admin1.php, see below).
Line 8: Closes the if statement created on the first line of this section.

CODE
    else {
        include("config.php");
    echo($no_pass_or_user_error_message);
    }

This "else" statement will echo an error message if either a username or password has not been entered (that is what the previous if statement was checking for).

admin1.php
This is the file where the validation is done. You will probably want more than one protected page so to create them simply copy this code into different files and change the content in the area where I have the PHP comment: //Any protected stuff you want goes in here!. Save the below as admin1.php
CODE
<?php
include("config.php");
$cookuser = $_COOKIE["cookuser"];
$cookpass = $_COOKIE["cookpass"];
$adminpass = md5($adminpass);
if($cookuser && $cookpass) {
    if(($cookuser == $adminuser) && ($cookpass == $adminpass)){
    echo("You have succesfully logged in! Please feel free to browse this secure admin page! To loggout go to <a href=logout.php>logout.php</a>");
    //Any protected stuff you want goes in here!
    }
    else{
    echo($incorrect_error_message);
    }
}
else{
echo($not_logged_in_message_error_message);
}
?>

Now for an explanation...
CODE
include("config.php");

Includes the config file.

CODE
$cookuser = $_COOKIE["cookuser"];
$cookpass = $_COOKIE["cookpass"];
$adminpass = md5($adminpass);

The first 2 lines set 2 variables, 1 each for the username and password which it retrieves from the cookies set in login.php (see above). The third line converts the admin password set in the config file (config.php, see above) into an md5 hash for added security.

CODE
if($cookuser && $cookpass) {
    if(($cookuser == $adminuser) && ($cookpass == $adminpass)){

The first if statement (line 1) checks to make sure there is actually some value to the variables $cookuser and $cookpass set above. The second if statement (line 2) checks to see if the username and password from the cookies match the username and password which are stored in the config file. If both the username and password match then the protected code/script will be executed:
CODE
echo("You have succesfully logged in! Please feel free to browse this secure admin page! To loggout go to <a href=logout.php>logout.php</a>");
    //Any protected stuff you want goes in here!


CODE
}

This ends the first if statement.

CODE
else{
    echo($incorrect_error_message);
    }

If either the username or password are incorrect this will display the error message set in the config file (see config.php above).

CODE
}
else{
echo($not_logged_in_message_error_message);
}

First line ends the 1st if statement set at the top of this whole file and then the other 3 lines is the else statement related to the if statement and it echos an error message.

logout.php
This is the last file, all it does is deletes the cookies and forwards to the login form so Im not even going to explain it. Save the below as logout.php
CODE
<?php
setcookie ("cookuser");  
setcookie ("cookpass");
header("Location: index.php");
?>


That's it, finitio, finir. All done. Click below to see the online, real working demo, username and password are demo.
Click here for the demo of all demos....]Click here for the demo of all demos....

Glad you read this and I sincerely hope you learnt something. If you have any questions/comments please don't hesitate to post them below.

-Adrian


IPB
 
+Quote Post  Go to the top of the page
thx1138
post May 4 2006, 12:07 PM
Post #2


New Member
Group Icon
Group: Member
Posts: 6
Joined: 20-April 06
Member No.: 10,852





Adrian;

Thanks for the updated version!

Here is a question...

How hard would it be to make this work for different logins "adminusers", (not using a password) Basically just
giving several office personal access to special intranet pages. I want them to feel like they have "special access codes" to get to these areas that are specific for each employee that have access. They do not have to know I cannot track them or anything, just so they know they all have different access codes to use.

So every person that would have "special" access would have a different user-id.

For example...
CODE
<?php
$user = "blabla1";
$user2 = "blabla2";
$user3 = "blabla3";

No passwords just a unique access name etc.

They would all go to the same pages that I choose to grant access to..


Just a little stupid thing I would like to try biggrin.gif .
Thanks for all your PHP stuff!

THX
 
+Quote Post  Go to the top of the page
Adrian
post May 4 2006, 12:31 PM
Post #3


Addicted Dot
Group Icon
Group: Moderator
Posts: 7,028
Joined: 26-September 04
Member No.: 763





mmmm, quite easy. First you would need to add those users (with those variable names) to the config file. Then when it comes to the admin1 file you would need to change the 2 main if statements to something like this:
CODE
if($cookuser) {
    if(($cookuser == $user1) or ($cookuser == $user2) or ($cookuser == $user3) or ($cookuser == $user4)){

That should work. You would also want to delete everything from all files relating to the passwords and it should still work. for each new user add or ($cookuser.... etc. Should all work.

It would be possible to use an array to store the users (and their passwords, if you wanted) but this would require alot of script changing so if you arent going to have too many users then this method should work fine but I wouldnt reccomend it for more than 10 users max. Plus if they dont have passwords its much easier to login.


IPB
 
+Quote Post  Go to the top of the page
thx1138
post May 5 2006, 09:48 AM
Post #4


New Member
Group Icon
Group: Member
Posts: 6
Joined: 20-April 06
Member No.: 10,852





Adrian:

Thanks for the tips... I currently have your code working by utilizing the "adminuser" only. I am now attempting to add multiple adminuser accounts as you have described. goggles[1].gif

Will update soon..

Thanks Again.


THX

Yes!
I have successfully manipulated the code to use multiple usernames without passwords dance.gif

Only one more questions.... g[1].gif

Is there a way to "kill" the cookie when the use the Logout link? That way they cannot just type in the addy again or keep going back and forth.?




THX
 
+Quote Post  Go to the top of the page
Adrian
post May 5 2006, 09:56 AM
Post #5


Addicted Dot
Group Icon
Group: Moderator
Posts: 7,028
Joined: 26-September 04
Member No.: 763





Posts merged. Please use the edit button next time!

The logout script doesnt delete the cookie. It deletes the information in it (the username and password) and if you return to the admin page in your browser (admin1.php) (after youve used the logout page) it will return with a not logged in error.


IPB
 
+Quote Post  Go to the top of the page
*D*
post May 15 2006, 11:12 AM
Post #6


Merry KissMoose
Group Icon
Group: Main Team
Posts: 15,988
Joined: 18-May 04
From: North Pole
Member No.: 2





Many thanks for the update Adrian. flowers.gif
 
+Quote Post  Go to the top of the page
mrrena
post Jun 6 2006, 12:44 AM
Post #7


New Member
Group Icon
Group: Member
Posts: 2
Joined: 6-June 06
Member No.: 11,556





Hello Adrian! fud.gif

Your tutorial was very helpful to me since I am have only dabbled a bit with PHP and the code worked very well for me within the same subdirectory. However, I ran into difficulties when I tried to use the code from the admin1.php page in files located in any other subdirectory other than the one in which the series of files comprising your tutorial live. Is there a way that the cookies can be made available globally so that the admin1.php code can be used in files located in any directory within a given domain? Specifically, I have the series of files parked in www.domain.com/adrian and I would like to be able to require admin login from files located in www.domain.com/alt_dir1 and www.domain.com/alt_dir2 as well. I have not been able to make it work in this way. The tutorials I have read elsewhere suggest that one can set cookies such that (for example):

CODE
setcookie ("cookuser", $formuser, $cookie_life, $path)


However, it appears that the validation you use in the following lines

CODE
$cookuser = $_COOKIE["cookuser"];
$cookpass = $_COOKIE["cookpass"];
$adminpass = md5($adminpass);
if($cookuser && $cookpass) {
    if(($cookuser == $adminuser) && ($cookpass == $adminpass))


would be thrown because the life of the cookie and its path would not neatly match up with just the password and username alone. The "path" variable appears to be most important in what I have read in terms of making the cookie available domain-wide (that is, the path variable set to "/"), but the big problem, really, is that I am rather incompetent and don't really know what I am doing. I flirt around with all kinds of Web work, but proceed as much by trial and error as any real skill. Would it be too much of a pain for you to offer me some pointers or guide me through? I'd happily learn, but going straight to the PHP documentation for a relative novice is daunting and a bit confusing: it assumes some level of learning and I am left scratching my head, more confused than when I started. Once one learns the language, English probably gets in the way but otherwise it would be nice is somebody spoke my native language as I am trying to learn. coffee.gif

Hoping to hear back from you soon...
Eric
 
+Quote Post  Go to the top of the page
Adrian
post Jun 8 2006, 12:32 PM
Post #8


Addicted Dot
Group Icon
Group: Moderator
Posts: 7,028
Joined: 26-September 04
Member No.: 763





Right. I think I know what your problem is and It's nothing to do with the cookies themselves. What is the error(s) you are getting when you try and have an admin file in, for example, www.domain.com/alt_dir1 instead of www.domain.com/adrian?

Tell me this and I'll tell you whats wrong.

Yes the php manual is very daunting for beginners. When i first started learning php some idiot said to me "just read the php manual!". At my current level of expertise I find it extremely useful but for 99.9% of beginners its way to scary!

Welcome to 13dots by the way!


IPB
 
+Quote Post  Go to the top of the page
mrrena
post Jun 9 2006, 12:01 AM
Post #9


New Member
Group Icon
Group: Member
Posts: 2
Joined: 6-June 06
Member No.: 11,556





Thanks for the reply, Adrian. smile.gif

What makes me think that it is likely a problem with the cookies is that it is triggering the error messages from your config.php file (and thus must be accessing those files, so the path information is correct). But I am sent in an endless loop, logging in only to be told I need to log in. Yet when I move that same admin file to the main directory where your file suite lives, I can log in and use the page as normal. In addition, the permissions are set the same for all directories involved. So these factors suggest to me that there was no coding error on my part that would have sent me into this endless loop. Now granted, it would not be the first time I'd sent myself into endless loops--sometimes I think that it the story of my programming life (smile)--but with as clear as your tutorial was and with these three troubleshooting steps eliminated... well, it's got me puzzled. Sad.gif
 
+Quote Post  Go to the top of the page
technovore
post Feb 19 2007, 01:31 AM
Post #10


New Member
Group Icon
Group: Member
Posts: 1
Joined: 19-February 07
Member No.: 15,039





This works great - thanks! There's only one problem which I can see in your demo. If the Username field is filled in and the Password field left blank, the "incorrect uername or password" error message is generated (not the "empty fields" message). It does work correctly if only the password is entered. Any idea why this might be?
 
+Quote Post  Go to the top of the page

Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

RSS