Solved

Authentication Script?

Posted on 2001-08-06
24
390 Views
Last Modified: 2008-03-06
Having just got a database up that stores user names and passwords, our non-profit group is looking for help on a php script that evaluates whether or not the user name and password is correct. If the password is correct, the script needs to somehow take people to a different web page of ours. Can php use a sort of [if password is correct then get url] type approach? Does anyone have a full script that does all of this?
0
Comment
Question by:rimbaud
  • 9
  • 9
  • 4
  • +1
24 Comments
 
LVL 15

Expert Comment

by:a.marsh
ID: 6357493
Yes it can easily do that - however you might want to go a bit further for example:

Let's say that a successful log in takes you to "welcome.html" and an unsuccessful login goes to "invalid.html".... doing a username and password check and then redirection is easy - but what if the user just types in "welcome.html" in the address bar? They'll be taken straight there! Bit of a "security loophole", wouldn't you say???

What you need is to use "sessions" aswell, and the welcome.html page would "check" that a session exists, if not redirect the user to the invalid.html page.

Make sense?

Let me know if that is the kind of functionality you want and then we can go from there.

:o)

Ant
0
 

Expert Comment

by:steveyoder
ID: 6357921
This code is for a mySQL database.
Try using the code below at the top of the page you want authenticated users to see. It makes your browser login box open and stores the users name and password as long as the current browser is open. If they don't have authorization the Access Denied page is loaded.
(Hope this helps!)

<?php
if ($PHP_AUTH_USER == "" && $PHP_AUTH_PW == "" &&
  ereg("^Basic ", $HTTP_AUTHORIZATION)) {
  list($PHP_AUTH_USER, $PHP_AUTH_PW) =
    explode(":", base64_decode(substr($HTTP_AUTHORIZATION, 6)));
}
 $authenticated = 0;
if ($PHP_AUTH_USER != "" || $PHP_AUTH_PW != "") {
  //authentication stuff (e.g. database lookup)
$hostname = "";
$access_username = "SomeUsername"; // This is a user account you create that has access to your database users table.
$access_password = "SomeUsernamesPassword";
$userstable = "mysql_authenticated_users"; //the name of your user table
$dbName = "YourDatabase";
   $db=MYSQL_CONNECT($hostname, $access_username, $access_password) OR DIE("Unable to connect to database");
   @mysql_select_db( "$dbName") or die( "Unable to select database");
   $result = mysql_query("SELECT * FROM $userstable WHERE username ='$PHP_AUTH_USER'and passwd='$PHP_AUTH_PW'");
   $myrow = mysql_fetch_array($result,$db);
   $username = $myrow["username"];
   $passwd = $myrow["passwd"];
   $authenticated = ($PHP_AUTH_USER == $username && $PHP_AUTH_PW = $passwd);
    mysql_free_result($result);

}
if(!$authenticated) {
  header("WWW-Authenticate: Basic realm=\"URLoad DB-Access\"");
  if (ereg("Microsoft", $SERVER_SOFTWARE))
    header("Status: 401 Unauthorized");
  else
    header("HTTP/1.0 401 Unauthorized");
  echo "<Center>";
  echo "<h1>Access Denied </h1><HR><br>";
  ?>
   <br>
  <a href="http://YourSite.com/lostpw.htm" ><b>Lost your username and password? Click here to get it back!</b></a>
  <br> <br>
  <a href="http://YourSite.com/new_user_form.php3" ><b>Click here if you want to get a username and password.</b></a>
</center>
<?
echo "</Center>";
  exit;
}
?>

0
 

Expert Comment

by:steveyoder
ID: 6358157
Sorry,
I didn't realize the etiquette here is to comment instead of answer.
Steve
0
 

Author Comment

by:rimbaud
ID: 6359712
a.marsh,
Yes, that is the thing I'm looking for.

-----------------------------------------------

Steveyoder,
I tried to implement the above the script, but had the below problems.

1)I get this when I run the script:

Warning: Cannot add header information - headers already sent by (output started at /www/buildingwithbooks/authenticate.php3:12) in
/www/buildingwithbooks/authenticate.php3 on line 38

Warning: Cannot add header information - headers already sent by (output started at /www/buildingwithbooks/authenticate.php3:12) in
/www/buildingwithbooks/authenticate.php3 on line 42

This is followed by "Access Denied" and all the remaining HTML in the script.


2) I don't see where in the script I can add the pages that users would be taken too.


3) How does lostpw.htm work?


4) I'm assuming you had a typo in $authenticated variable where it says passwd='$PHP_AUTH_PW.' That should be an equal to (==) operator, no?
0
 
LVL 15

Expert Comment

by:a.marsh
ID: 6359755
0
 

Expert Comment

by:ComTech
ID: 6359953
Hi steveyoder, Please read Comment vs. Answers at the bottom of the page, especially the link provided. We perfer the comment button and let the user choose the comment he/she likes the best.

Thank you,
ComTech
Community Support
Moderator
0
 

Expert Comment

by:steveyoder
ID: 6362314
Please accept my humble apology, I didn?t mean to cause such a ruckus.  Comments only from now on!

a.marsh, I?m afraid the code won?t work on the Win32 Binary version of PHP, sorry.  For full functionality you need the more robust LINUX/UNIX version.  If you don?t use the Win32 Binary version of PHP on your web site then this will work for you. The same type of authentication can be used with the Win32 Binary version but without the cool, built-in pop-up window.
To address point # 4 from a.marsh, I?m sorry but that?s not a typo.  One equal sign is all you need in the SQL (structured query language) part of the ?mysql_query? function.

To see an example of this code go to http://urload.com and click the ?List a Load? button. (This is a truck/load matching service that is under development, go ahead and play around with it.)
In the ?Enter Network Password? box enter the username: testuser and password: testuser
This then takes you to the page I have chosen for authenticated users to access.  They also have access to the rest of the information they own without having to login repeatedly.
When you get done playing around with it, close your browser, restart it and enter any other username and password. Unless you are extremely lucky at guessing you will be directed to the ACCESS DENIED page after 3 failed login attempts.

Since you are a non-profit group I would be happy to share the code with you.  I?m sure you?ll find it does exactly what you are looking for.  I also wrote code to have lost passwords emailed to the password owner?s e-mail address.  You can have that too if you like. Send me a note and I?ll get them to you.
Sincerely,
Steve Yoder
0
 

Expert Comment

by:steveyoder
ID: 6362749
P.S. Don't paste your text here from a Microsoft Word document, the apostrophes and commas will change to question marks.

;>
0
 

Expert Comment

by:ComTech
ID: 6364531
Hi steveyoder, I went through the same thing myself, most of us do.  :-)

Welcome
ComTech
Community Support

Sorry for the interruption.
0
 

Author Comment

by:rimbaud
ID: 6365104
Steve,

Yes,
The authentication process that the truck/load matching site uses would be great. Our organization would love to try using that code, and the code for lost passwords. Nothing else seems to work, so I'm leary that I can get it configured correctly, but that would be great if you could send these scripts over if it works using php and mySQL! Is it as complex as the previous script you send?
0
 

Expert Comment

by:steveyoder
ID: 6366661
Send me a note at steveyoder@home.com and I'll send them along with some instructions.
Remember, this won't work on Windows NTs IIS. What kind of operating system and web server are you using?
0
 

Author Comment

by:rimbaud
ID: 6369840
Actually,

I managed to find a script that works--a php3 script on ou--linux box. Even though we can run php4, all those scripts seems too difficult to implement for someone like me who has no php4 experience.

Anyway, this works, but all it does is deny or accept password. I still need to get it to send users off to a new page if they are authenticated. Is there some simple code that can be added to this script to make that work?



<html>
<head>
    <title>Password Checking Script</title>

</head>
<body>
<?php
function print_form() {
    ?>
    <form action="check_password.php3" method="POST">
    <h3>Please Login</h3>
    User Name: <input type="text" name="user_name">
    <br>Password: <input type="password" name="password">
    <input type="submit" name="submit" value="Login!">
    </form>
    <?
}

if(isset($submit)):
    if(!$db = mysql_connect("db","username", "password")):
        print("<h1>Can't Connect to the DB!</h1>\n");
    else:
        mysql_select_db("table", $db);
    endif;
    $sql = "select * from table where field = '$user_name'";
    $result = mysql_query($sql);
    $row_count = mysql_num_rows($result);
    if($row_count == 0):
        ?>
        <h3>Wrong User Name! Try Again</h3>
        <?
        print_form();
    else:
      $row = mysql_fetch_array($result);
      if($password != $row["password"]):
        ?>
        <h3>Incorrect Password! Try Again</h3>
        <?
        print_form();
      else:
        ?>
        <h3>Password Accepted!</h3>
     
        <?
      endif;
    endif;
else:
print_form();
endif;
?>
</body>
</html>
0
Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

 
LVL 15

Expert Comment

by:a.marsh
ID: 6369860
Well it's not the most secure way of doing things i.e. if the user knows the name of the page that they get redirected to they can go straight there and bypass the login.

Did you take a look at the link I gave earlier?

:o)

Ant
0
 

Author Comment

by:rimbaud
ID: 6369931
So there's no php3 code that makes things secure? Does it have to be php4 to do the authenticated redirect?

If it has to be php4, i can still use this code with some slight syntax changes so it works in php4, and then add the authentication redirect code.

I'm just wondering if there is a simple block of code that does all the redirect stuff and hides the URL address like I'm looking for.
0
 
LVL 15

Expert Comment

by:a.marsh
ID: 6369985
It's not going to be quite that simple I'm afraid - take a look at:

http://www.phpsecurepages.f2s.com/

Hopefully you will find it helpful enough to get working.

:o)

Ant
0
 

Accepted Solution

by:
steveyoder earned 250 total points
ID: 6370516
All you need to do is make a "login" link on the main page that points to the page you want authenticated users to go to. Put the authentication script at the top of the file or use "include("your_auth_script.php3");" and save the code in your include directory as your_auth_script.php3. If the user makes it through the authentication script the code continues on to the page you want him or her to see. If the user fails at the authentication script they can only see the ACCESS DENIED part of the "if" statement and the code does not proceed to the page you want secured. Put the "include("your_auth_script.php3");" line at the top of every file you want protected in this way and you'll be secure against people just typing filenames into the web browser. Since the browser holds the Name and Password variables until it's closed the user can breeze through locked pages without having to login every time.
I hope I'm not rambling on too much.
Good luck!
0
 

Author Comment

by:rimbaud
ID: 6372681
Steve,

Not rambling at all. This idea speaks towards the answer I'm looking for. I tried what you said--made a link that says login with the URL to the page they should go to, put the check password include on both the login page and page they should go to. Problem is that the page comes up with the user id and password input forms and the page directly below the forms. So it's not doing the script first but rather displaying the php checker and the page all at once.

I made a stupid example link and secure page to test this. Check out: http://www.buildingwithbooks.org/login.html

0
 

Expert Comment

by:steveyoder
ID: 6375026
rimbaud,
Are you using the Win32 binary version of PHP? What kind of operating system runs the web server? It would help me to know what you've got to work with. If you don't know what you've got, paste this into a file <?php phpinfo() ?> , name it something with a .php extention and send me the link.
Let me see the code you wrote, for the donut test page. Might be a problem with your IF statement or something simple.

Here's the lost username/password stuff (It ain't pretty but it works.):

First file (lostpw.htm)- Input Form

<HTML>
<HEAD>
<TITLE>Lost User Name and Password</TITLE>
<body><CENTER>
<H1>Forgot your User Name or Password? No Problem!</H1><HR>
<P>
<TABLE border=0><CENTER>
<FORM ACTION="email.php3" METHOD="POST">
<tr><td>  
Please enter the email address you used to set up your account. <BR><tr><td>
<CENTER><INPUT TYPE="text" NAME="email" SIZE="50" MAXLENGTH="50">
<tr><td><CENTER>
<INPUT TYPE="submit" VALUE="Go Get It">
</CENTER></td></tr>
</FORM>
</TABLE>
<br>
If you are in need of additional assistance please contact:
<a href="mailto:YourWebmaster@donut.com">Donut Support</a><br>
</BODY>
</HTML>

Second file (email.php3)

<HTML>
<HEAD>
<TITLE>Request User Name and Password</TITLE>
<body><CENTER>
<?
/* the site administrator's email address */
$adminaddress = "webmaster@YourWebsite.com";

/* make connection to database */

/* Now you'll want to set these variabls to login to the DB (I use an include(filename.inc); here.) */
$db=MYSQL_CONNECT($hostname, $access_username, $access_password) OR DIE("Unable to connect to database");
@mysql_select_db("$dbName") or die("Unable to select database");

$mailresult=MYSQL_QUERY("select * from auth_table where email='$email'");

if ($myrow = mysql_fetch_array($mailresult)) {
     $username = $myrow["username"];
     $passwd = $myrow["passwd"];
     echo "<H3>A message has been sent to <b>$email</b></H3>";
        include("confirmation_page.php3");
/* Send relevant emails */

mail("$email", "Your request for information", "Thank you for using MyWebSite!\nPlease do not respond to this e-mail.\nIf you require additional assistance please contact: \nWebMaster@MyWebsite.com. \nYour User Name is $username and your Password is $passwd. \nThanks and come again!\n","From: webmaster@MyWebsite.com\nReply-To: webmaster@MyWebsite.com\nX-Mailer: PHP/" . phpversion());

$fullname = $myrow["fullname"];
$date = (date("d M Y h:i:s A"));

/* This code will send a notification to the administrators address */

mail("$adminaddress","Visitor request for info.",
"$fullname requested Username and Password on $date.\n
The email address is $email. \n ","From: webmaster@MyWebsite.com\nReply-To: webmaster@MyWebsite.com\nX-Mailer: PHP/" . phpversion());
}else{
}
/* Close the database connection */
MYSQL_CLOSE();
?>
</BODY>
</HTML>

Good Luck!
Steve Yoder
0
 

Expert Comment

by:steveyoder
ID: 6375074
rimbaud,
Are you using the Win32 binary version of PHP? What kind of operating system runs the web server? It would help me to know what you've got to work with. If you don't know what you've got, paste this into a file <?php phpinfo() ?> , name it something with a .php extention and send me the link.
Let me see the code you wrote, for the donut test page. Might be a problem with your IF statement or something simple.

Here's the lost username/password stuff (It ain't pretty but it works.):

First file (lostpw.htm)- Input Form

<HTML>
<HEAD>
<TITLE>Lost User Name and Password</TITLE>
<body><CENTER>
<H1>Forgot your User Name or Password? No Problem!</H1><HR>
<P>
<TABLE border=0><CENTER>
<FORM ACTION="email.php3" METHOD="POST">
<tr><td>  
Please enter the email address you used to set up your account. <BR><tr><td>
<CENTER><INPUT TYPE="text" NAME="email" SIZE="50" MAXLENGTH="50">
<tr><td><CENTER>
<INPUT TYPE="submit" VALUE="Go Get It">
</CENTER></td></tr>
</FORM>
</TABLE>
<br>
If you are in need of additional assistance please contact:
<a href="mailto:YourWebmaster@donut.com">Donut Support</a><br>
</BODY>
</HTML>

Second file (email.php3)

<HTML>
<HEAD>
<TITLE>Request User Name and Password</TITLE>
<body><CENTER>
<?
/* the site administrator's email address */
$adminaddress = "webmaster@YourWebsite.com";

/* make connection to database */

/* Now you'll want to set these variabls to login to the DB (I use an include(filename.inc); here.) */
$db=MYSQL_CONNECT($hostname, $access_username, $access_password) OR DIE("Unable to connect to database");
@mysql_select_db("$dbName") or die("Unable to select database");

$mailresult=MYSQL_QUERY("select * from auth_table where email='$email'");

if ($myrow = mysql_fetch_array($mailresult)) {
     $username = $myrow["username"];
     $passwd = $myrow["passwd"];
     echo "<H3>A message has been sent to <b>$email</b></H3>";
        include("confirmation_page.php3");
/* Send relevant emails */

mail("$email", "Your request for information", "Thank you for using MyWebSite!\nPlease do not respond to this e-mail.\nIf you require additional assistance please contact: \nWebMaster@MyWebsite.com. \nYour User Name is $username and your Password is $passwd. \nThanks and come again!\n","From: webmaster@MyWebsite.com\nReply-To: webmaster@MyWebsite.com\nX-Mailer: PHP/" . phpversion());

$fullname = $myrow["fullname"];
$date = (date("d M Y h:i:s A"));

/* This code will send a notification to the administrators address */

mail("$adminaddress","Visitor request for info.",
"$fullname requested Username and Password on $date.\n
The email address is $email. \n ","From: webmaster@MyWebsite.com\nReply-To: webmaster@MyWebsite.com\nX-Mailer: PHP/" . phpversion());
}else{
}
/* Close the database connection */
MYSQL_CLOSE();
?>
</BODY>
</HTML>

Good Luck!
Steve Yoder
0
 

Author Comment

by:rimbaud
ID: 6383869
0
 

Author Comment

by:rimbaud
ID: 6383919
Also here are the two files I made for the php3 test...

<b>First: http://www.buildingwithbooks.org/login.html</b>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<?php
include("check_password.php3");
?>
<html>
<head>
     <title>login</title>
</head>

<body>

<a href="http://www.buildingwithbooks.org/donutsFinal.php3">Please log in.
</a>
</body>
</html>

---------------------------------------------


<b>Second: http://www.buildingwithbooks.org/donutsFinal.php3</b>


<?php
include("check_password.php3");
?>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>

</HEAD>
<BODY>


<SCRIPT language="JavaScript">
//document.writeln("You selected ");
function validate(){
    var i,j
    var num = document.donuts.fav.length
    for(i=0;i<num;i++){
         if(document.donuts.fav[i].checked==true){
              j = i
              break;
         }
    }
    //alert(j)
    var taste = document.donuts.fav[j].value
    //alert(taste)  if I use j instead of taste below, I get an index number instead of value
    document.write("<table><tr><td>" + "You selected " + taste + "</td></tr></table>");
}

</SCRIPT>

</HEAD>

<BODY>
What is your favorite donut?&nbsp;&nbsp;&nbsp;
<FORM name="donuts">
    <INPUT type="radio" name="fav" value="jelly">jelly<BR>
    <INPUT type="radio" name="fav" value="glazed" >glazed<BR>
    <INPUT type="radio" name="fav" value="cruller">cruller<BR>
    <INPUT type="radio" name="fav" value="chocolate">chocolate<p>
    <INPUT type="button" onClick="validate()" value="submit">
</FORM>
</BODY>
</HTML>
0
 

Author Comment

by:rimbaud
ID: 6383940
Whoops! sorry, my html forced tags made all the code a link. This should look normal.




Also here are the two files I made for the php3 test...

First: http://www.buildingwithbooks.org/login.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<?php
include("check_password.php3");
?>
<html>
<head>
     <title>login</title>
</head>

<body>

<a href="http://www.buildingwithbooks.org/donutsFinal.php3">Please log in.
</a>
</body>
</html>

---------------------------------------------


Second: http://www.buildingwithbooks.org/donutsFinal.php3


<?php
include("check_password.php3");
?>
<HTML>
<HEAD>
<META NAME="GENERATOR" Content="Microsoft Visual Studio 6.0">
<TITLE></TITLE>

</HEAD>
<BODY>


<SCRIPT language="JavaScript">
//document.writeln("You selected ");
function validate(){
    var i,j
    var num = document.donuts.fav.length
    for(i=0;i<num;i++){
         if(document.donuts.fav[i].checked==true){
              j = i
              break;
         }
    }
    //alert(j)
    var taste = document.donuts.fav[j].value
    //alert(taste)  if I use j instead of taste below, I get an index number instead of value
    document.write("<table><tr><td>" + "You selected " + taste + "</td></tr></table>");
}

</SCRIPT>

</HEAD>

<BODY>
What is your favorite donut?&nbsp;&nbsp;&nbsp;
<FORM name="donuts">
    <INPUT type="radio" name="fav" value="jelly">jelly<BR>
    <INPUT type="radio" name="fav" value="glazed" >glazed<BR>
    <INPUT type="radio" name="fav" value="cruller">cruller<BR>
    <INPUT type="radio" name="fav" value="chocolate">chocolate<p>
    <INPUT type="button" onClick="validate()" value="submit">
</FORM>
</BODY>
</HTML>
0
 

Author Comment

by:rimbaud
ID: 6398949
Steve,
Using a combination of things you suggested I was able to fashion a solution. Thanks for all your correspondence, feedback, and persistence.
0
 

Expert Comment

by:steveyoder
ID: 6408460
It's my pleasure and I'm happy that I could help.
Thanks for the points, you know I'm new to this scene.
Sincerely,
Steve Yoder
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now