Avatar of StateGuy
StateGuy
Flag for United States of America asked on

Coding a secure(?) login using MySQL and PHP

I'm new to PHP and am trying to code a site where I have a browser-generated login box, calling a username and password from a MySQL database.  After a VERY long time of looking on the web to find code that I could use, I've tried every code sample I found.  Both "as-is" and modified, but nothing worked as described.  I'm comfortable with this piece, but I can't get it to see the username or password to allow me to get logged in.  This is a difficult question for me, but might be fairly straightforward for the experts.  I'll need more help later, and I'm running out of points to assign, so I'm only giving it a "This question is moderately difficult" level.  If you guys think it's worth more, please let me know and I'll up it appropriately.  

My code is attached: LoginNumber2.txt

I'd really appreciate any help I can get.

Randy

LoginNumber2.txt
PHPMySQL Server

Avatar of undefined
Last Comment
StateGuy

8/22/2022 - Mon
StateGuy

ASKER
Oops.  The MySQL code has an error.  The "Username" field should be 255, not 8.
Ludatha

This is how I would do it.

When someone registers, their password is turned into a md5 hash, so if you look in the databse, it is not readable.

Attached, I have written you a secure login script, just define your ariables for the database and change the values!
If I have made any errors, please tell me and ill fix them.
<?php
//************************************************
//************ Change these values ***************
//************************************************
 
$host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
$database = "aap";
$table = "Users";
$UserFieldName = "Username";
$PasswordFieldName = "Password";
 
//************************************************
//************************************************
//************************************************
 
function login($username,$password)
{	
	mysql_connect("$host", "$mysql_user", "$mysql_pass")or die("cannot connect");
	mysql_select_db("$database")or die("cannot select DB");
	
	$password=md5($password);
	$sql="SELECT * FROM $table WHERE $UserFieldName='$username' AND $PasswordFieldName='$password'";
    $result=mysql_query($sql);
	$result = mysql_num_rows($result);  
	
if($result!="0"){ 
	$_SESSION["password"] = $password;
	$_SESSION["username"] = $username;
	echo "You are Logged In!";
	}
	else 
	{
		echo "Wrong username or password. Please try again!";
	}
}
 
if(isset($_GET["submit"]))
{
	$user = mysql_real_escape_string($_POST['username']); 
	$pass = mysql_real_escape_string($_POST['password']);
	login($_POST["username"],$_POST["password"]);
}
?>

Open in new window

StateGuy

ASKER
The original that I posted had a call to "login.php" at the top of every page to ensure the page was being accessed by an authorized, logged in user. I apologize for omitting that.  Ultimately, this will be for a three-screen app where all three screens need to be protected.

With this code, do I need to create a login screen?  I've got one I can use, but I don't want to try anything at this point without someone telling me what to do.  This whole thing has me slightly paranoid.  I tried to run your code by loading it into a single file that I called "login.php," but it just showed a blank screen.  

I'm beginning to think I bit off more than I could chew.
Your help has saved me hundreds of hours of internet surfing.
fblack61
Ludatha

The code I have posted just processes the login, all you need to do is add a form that has a username, password feilds and sa submit button, here is the whole code with the form.

Now, I would like to add, instead of havving a php script running every time a page loads to keep you logged in, all you have to do with this script is put
session_start();
at the top of every page.

If you want, I can code you a secure registration script and logout script that merge with this login script perfectly. (they are the ones I use on my website)

I have commented the code as much as possible to help to a bit. And if there are any errors, please tell me and ill fix the for you :)

If
session_start();
<?php
//************************************************
//************ Change these values ***************
//************************************************
 
$host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
$database = "aap";
$table = "Users";
$UserFieldName = "Username";
$PasswordFieldName = "Password";
 
//************************************************
//************************************************
//************************************************
 
function login($username,$password) // function to login
{       
        mysql_connect("$host", "$mysql_user", "$mysql_pass")or die("cannot connect");
        mysql_select_db("$database")or die("cannot select DB"); // Connect to the database
        
        $password=md5($password); // Encrypt the password from the form
        $sql="SELECT * FROM $table WHERE $UserFieldName='$username' AND $PasswordFieldName='$password'"; // SQL to check if the user exsists
    	$result=mysql_query($sql); // Perform the MySQL query
        $result = mysql_num_rows($result);  // See if it exsists
        
if($result!="0"){ // If it does exsist
        $_SESSION["password"] = $password; // Register the password to the session
        $_SESSION["username"] = $username; // Register the username to the session
        echo "You are Logged In!"; // Tell the user that they are logged in
        }
        else // But if it doesnt exsist
        {
                echo "Wrong username or password. Please try again!"; // Tell them they are wrong
        }
}
 
if(isset($_GET["submit"]))
{
        $user = mysql_real_escape_string($_POST['username']); // Prevent MySQL Injection, for the username, and set the variable
        $pass = mysql_real_escape_string($_POST['password']); // Prevent MySQL Injection, for the password, and set the variable
        login($user, $pass); // Call the function, Login.
}
?>
<!-- Now for the form -->
<form method="post" action="login.php?submit"> 
  &nbsp;Username&nbsp;<input type="text" name="username" id="username"/>
  &nbsp;Password&nbsp;<input type="password" name="password" id="password"/>
  <input type="submit" value="LOGIN"/>
</form>

Open in new window

StateGuy

ASKER
If you can do that and I can figure out how to run it, name your points... seriously.  I've got 503 left, until I can afford more anyway, and I'll pass them all along to you.  I'll load this up with my login form and see how it runs.  I'm fairly limited to evenings (west coast, USA) for checking my email.

Randy
StateGuy

ASKER
I had to put "session_start();" into the "<?php ?>" block.  

I got these errors:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\xampplite\htdocs\webs\SecureLoginNumber3\login.php on line 43

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in C:\xampplite\htdocs\webs\SecureLoginNumber3\login.php on line 43

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\xampplite\htdocs\webs\SecureLoginNumber3\login.php on line 44

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in C:\xampplite\htdocs\webs\SecureLoginNumber3\login.php on line 44

Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\xampplite\htdocs\webs\SecureLoginNumber3\login.php on line 22
cannot connect

Any ideas?

PS:  I'm all in.  500 points for an answer.  That leaves me with three and payday's a week away.

Randy
<?php
session_start();
 
//************************************************
//************ Change these values ***************
//************************************************
 
$host = "localhost";
$mysql_user = "root";
$mysql_pass = "";
$database = "aap";
$table = "Users";
$UserFieldName = "Username";
$PasswordFieldName = "Password";
 
//************************************************
//************************************************
//************************************************
 
function login($username,$password) // function to login
{       
        mysql_connect("$host", "$mysql_user", "$mysql_pass")or die("cannot connect");
        mysql_select_db("$database")or die("cannot select DB"); // Connect to the database
        
        $password=md5($password); // Encrypt the password from the form
        $sql="SELECT * FROM $table WHERE $UserFieldName='$username' AND $PasswordFieldName='$password'"; // SQL to check if the user exsists
    	$result=mysql_query($sql); // Perform the MySQL query
        $result = mysql_num_rows($result);  // See if it exsists
        
if($result!="0"){ // If it does exsist
        $_SESSION["password"] = $password; // Register the password to the session
        $_SESSION["username"] = $username; // Register the username to the session
        echo "You are Logged In!"; // Tell the user that they are logged in
        }
        else // But if it doesnt exsist
        {
                echo "Wrong username or password. Please try again!"; // Tell them they are wrong
        }
}
 
if(isset($_GET["submit"]))
{
        $user = mysql_real_escape_string($_POST['username']); // Prevent MySQL Injection, for the username, and set the variable
        $pass = mysql_real_escape_string($_POST['password']); // Prevent MySQL Injection, for the password, and set the variable
        login($user, $pass); // Call the function, Login.
}
?>
<!-- Now for the form -->
<form method="post" action="login.php?submit"> 
  &nbsp;Username&nbsp;<input type="text" name="username" id="username"/>
  &nbsp;Password&nbsp;<input type="password" name="password" id="password"/>
  <input type="submit" value="LOGIN"/>
</form>

Open in new window

⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
Ludatha

Are you sure the dabase infomation is corrent, like your username and password.
You really should have a password on your database.

Sorry about that session_start();

I will get the full script up as I said in a few hours, I've been very busy, sorry about that.
Ludatha

Ok, it's done. It is 4kb in total.
Thing is, I cannot upload .zip files, so may I have you email so I can attach it to that?
My email is zoglander@gmail.com.


StateGuy

ASKER
randy.worrell@comcast.net.  And the 500 points is serious.  I need to get this licked ASAP.  I appreciate your help and once I get the code I'll let you know as soon as I can run it.

Thanks again.

Randy
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
StateGuy

ASKER
I found that it threw an error if I left the "mysql_real_escape_string()" function in:

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\xampplite\htdocs\webs\SecureLoginNumber4\login.php on line 37

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in C:\xampplite\htdocs\webs\SecureLoginNumber4\login.php on line 37

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'ODBC'@'localhost' (using password: NO) in C:\xampplite\htdocs\webs\SecureLoginNumber4\login.php on line 38

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in C:\xampplite\htdocs\webs\SecureLoginNumber4\login.php on line 38
Wrong username or password. Please try again!

But it worked if I dropped the "mysql_real_escape_string" function.  I didn't change anything between tests, just dropped the function.  I don't know why it worked, but it did.  Of course if I KNEW why, I wouldn't need help.  Anyway, I'm testing it right now and should be done with my first round of testing by Monday.  It's that other thing called "life" that's slowing me down. :)

I REALLY appreciate your help.  Talk to you soon.

Randy

if(isset($_GET["submit"])) // if ?submit is on the end of the url
{
		//$user = mysql_real_escape_string($_POST['username']); // Prevent MySQL Injection, for the username, and set the variable
        //$pass = mysql_real_escape_string($_POST['password']); // Prevent MySQL Injection, for the password, and set the variable
 
        $user = $_POST['username']; // Prevent MySQL Injection, for the username, and set the variable
        $pass = $_POST['password']; // Prevent MySQL Injection, for the password, and set the variable
        
        login($user, $pass); // Call the function, Login.
}

Open in new window

StateGuy

ASKER
I modified the code in "login.php" like this:

if($result!="0"){ // If it does exsist
        $_SESSION["password"] = $password; // Register the password to the session
        $_SESSION["username"] = $username; // Register the username to the session
       
      (I commented out this line...)
        //echo "You are Logged In!"; // Tell the user that they are logged in
      (...and inserted this line)
        header("Location: test.php");
       
        }
        else // But if it doesnt exsist
        {
                echo "Wrong username or password. Please try again!"; // Tell them they are wrong
(an attempt to blow away the session to prevent the "test.php" page from loading outside of a good login)
              session_start();
                session_destroy();
        }
} // End of function

I created a test file to be called by a successful login, "test.php:"
<?php
session_start();
echo "You are Logged In!"; // Tell the user that they are logged in
?>

Logging in with the correct username and password worked; logging in with either a bad username or password correctly told me I didn't get logged in.  But when I logged in with a bad username or password, I called "test.php" immediately by itself to see if it would require a login.  It still came up as if I had a successful login.  So thinking I had an idea, I modified "test.php" to:
<?php
//session_start();
if (!session_start())
{
      header("Location: login.php");
}
else
{
      echo "You are Logged In!"; // Tell the user that they are logged in
}
?>

It still worked when I had a legit login, but when I had a bad login, I tried calling "test.php" directly again, and it still came up as if I had a legit login, when in fact the login was rejected by "login.php."  In this instance, I want "test.php" to not come up if I go to it directly outside of a valid login.  Am I now getting into the realm of cookies?

I seem to be getting closer, but I still feel my lack of PHP knowledge is killing me.

Randy
Ludatha

I don't know why the "mysql_real_escape_string" didn't work for you...
I only put that there because you wanted it to be secure.

mysql_real_escape_string, this command secures post variables so when infomation is passed over it cannot be edited, this is called MySQL injection.
http://php.net/mysql_real_escape_string

The only reason I can think of why it doesnt work is because of the charecter encoding.

Now about your second post,

header("Location: test.php");
It is OK to use that function, but I do recomend javascript redirects, because you do get alot of "headers already sent" errors.

As for cookies, I am not an expert on those, probably because of being able to hack a cookie and changing infomation.

I really do recomend signing up to this website: http://codingforums.com/forumdisplay.php?f=6

They have helped me sooo much.


Ok, now I DO have a fix for your login issue :)
at the top of every page (or if you use headers and footers, just put it in the header)
put this code:

$loggedin = false;
if(session_is_registered("username") && session_is_registered ("password"))
{
      $loggedin = true;
}

now on any page you can allow people who are registered or not to view pages.

if you want a page only avalible for people who are logged in:

if($loggedin==true){
            // if they are logged in do this code
      }
      else
      {
            or if they are not logged in then display this code
      }

I hope this works for you.

- Adam
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
StateGuy

ASKER
I looked up SQL Injection Attacks and agree that I should find a way to make it work.  I'll work on that end more later.  But right now it seems to be working.  Here's what I've done; please tell me if it looks right.

First, I created a MySQL database user with rights to only the specific database.  Right now, that's called "aap" with a password.  That's what I put into DbVars.php:
<?php
// File: DbVars.php
// File Version: 1.0.1.0
// Date Revised: 23/04/2008 12:23 PM
// Coded by: Adam Tester
// Copyright Ludatha 2008 (http://www.ludatha.com)

$host = "localhost";
$mysql_user = "aap";
$mysql_pass = "szExM9tEMjNEAbwm";
$database = "aap";
$table = "users";
$UserFieldName = "username";
$PasswordFieldName = "password";

DEFINE ('DB_USER', $mysql_user);
DEFINE ('DB_PASSWORD', $mysql_pass);
DEFINE ('DB_HOST', $host);
DEFINE ('DB_NAME', $database);
DEFINE ('DB_TABLE', $table);
DEFINE ('DB_USER', $UserFieldName);
DEFINE ('DB_PASS', $PasswordFieldName);
?>

Next, I made a very minor change in login.php by adding a session variable: "$_SESSION["loggedin"] = true;", adding a header() redirect on a successful login "header("Location: test.php");" and destroying the session on a bad login: "session_destroy();"
<?php
// File: login.php
// File Version: 1.0.2.0
// Date Revised: 23/04/2008 12:30 PM
// Coded by: Adam Tester
// Copyright Ludatha 2008 (http://www.ludatha.com)

session_start();
 
function login($username,$password) // function to login
      {  
            require_once("includes/DbVars.php");

            mysql_connect("$host", "$mysql_user", "$mysql_pass") or die ("Query failed: " . mysql_error());
        mysql_select_db("$database") or die ("Cannot select DB: " . mysql_error()); // Connect to the database

        $password=md5($password); // Encrypt the password from the form
        $sql="SELECT * FROM $table WHERE $UserFieldName='$username' AND $PasswordFieldName='$password'"; // SQL to check if the user exsists
        $result=mysql_query($sql); // Perform the MySQL query
        $result = mysql_num_rows($result);  // See if it exsists

            if($result!="0")
                  { // If it does exsist
                    $_SESSION["password"] = $password; // Register the password to the session
                    $_SESSION["username"] = $username; // Register the username to the session
                    $_SESSION["loggedin"] = true;

                    //echo "You are Logged In!"; // Tell the user that they are logged in
                    header("Location: test.php");
              }
        else // But if it doesnt exsist
              {
                session_destroy();
                echo "Wrong username or password. Please try again!"; // Tell them they are wrong
              }
} // End of function

if(isset($_GET["submit"])) // if ?submit is on the end of the url
      {
            //$user = mysql_real_escape_string($_POST['username']); // Prevent MySQL Injection, for the username, and set the variable
        //$pass = mysql_real_escape_string($_POST['password']); // Prevent MySQL Injection, for the password, and set the variable

        $user = $_POST['username']; // Prevent MySQL Injection, for the username, and set the variable
        $pass = $_POST['password']; // Prevent MySQL Injection, for the password, and set the variable
       
        login($user, $pass); // Call the function, Login.
      }
?>

<!-- Put my form stuff here down -->

<br>Please Login<br/>

<!-- Now for the form -->
<form method="post" action="login.php?submit">
  &nbsp;Username&nbsp;<input type="text" name="username" id="username"/><br/>
  &nbsp;Password&nbsp;<input type="password" name="password" id="password"/><br><br/>
  <input type="submit" value="LOGIN"/>
</form>

I twiddled with logout.php to redirect to the login page:
<?php
session_start();
session_destroy();
header("Location: login.php");
?>

I created two pages to test the login capability: test.php and test2.php.
test.php:
<?php
session_start();
if ($_SESSION["loggedin"] != true)
      {
            header("Location: login.php");
      }
else
      {
            echo "You are Logged In, page 1!"; // Tell the user that they are logged in
      }
?>
<!-- Page to be accessed only by valid login -->
<form method="post" action="test2.php">
  <input type="submit" value="Page 2"/>
</form>      
<form method="post" action="logout.php">
  <input type="submit" value="Logout"/>
</form>

test2.php:
<?php
session_start();
if ($_SESSION["loggedin"] != true)
      {
            header("Location: login.php");
      }
else
      {
            echo "You are Logged In, page 2!"; // Tell the user that they are logged in
      }
?>
<!-- Page to be accessed only by valid login -->
<form method="post" action="test.php">
  <input type="submit" value="Page 1"/>
</form>      
<form method="post" action="logout.php">
  <input type="submit" value="Logout"/>
</form>

When I try to access either test.php or test2.php outside of a successful login, I'm automatically kicked back to the login page.  If I have a successful login, I can navigate to either page without a problem.  I guess my questions are down to:
1) Is the session variable ($_SESSION["loggedin"]) a valid, secure way of protecting the pages I need to protect?
2) Is DbVars.php in a secure location for a web site ("includes" directory)?
3) Is using "header("Location: test.php");" OK as long as I don't get header errors?  (So far it's working fine.  I haven't had any errors using it.)
and finally,
4) On a scale of 1 to 10, how secure would this be, "as-is," for preventing someone from getting to either "test.php" or "test2.php" outside of a valid login?  The most sensitive data that could be accessed in the whole application would be name, address and phone numbers.  No SSNs, financial account numbers, etc.

Thanks, bud.  It looks like it's getting down to the end.

Randy
StateGuy

ASKER
Now that this is working, I'm trying to grab the ID value from the result set and put it into a session variable for use on subsequent pages.

        $sql="SELECT * FROM $table WHERE $UserFieldName='$username' AND $PasswordFieldName='$password'"; // SQL to check if the user exsists
        $result=mysql_query($sql); // Perform the MySQL query
        $result = mysql_num_rows($result);  // See if it exsists

            if($result=="1")
                  { // If it does exsist
                        $_SESSION["password"] = $password; // Register the password to the session
                    $_SESSION["username"] = $username; // Register the username to the session
                    $_SESSION["loggedin"] = true;
                    $_SESSION["id"] = $row['ID']; // Register the key field to the session

                    //echo "You are Logged In!"; // Tell the user that they are logged in
                    header("Location: test.php");
              }

I echo "$_SESSION["id"] " on the page that pops up after a successful login, but there's no value in it.  Is the line "$_SESSION["id"] = $row['ID'];" the correct way to assign it?  From what I've seen and read it is, but it's not loading into the session variable.  What am I doing wrong?

StateGuy

ASKER
Clarification:
The line "if($result=="1")" wasn't an issue.  I changed it back to "if($result!="0")" and still got the same result.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Ludatha

Ok, looks like your comming on well :)

So I'll answer all your questions in your 1st post.

"1) Is the session variable ($_SESSION["loggedin"]) a valid, secure way of protecting the pages I need to protect?"

Yes, but bear in mind that any user (if they know how) can destroy the session at any time, but not set it.


"2) Is DbVars.php in a secure location for a web site ("includes" directory)?"

Now this depends on your server, generally without special toolds, you cannot download a php file and get the data from it, but I recomend you set different permissions for this file (try 600)
I also recomend you encrypt the file using: http://www.byterun.com/free-php-encoder.php


"3) Is using "header("Location: test.php");" OK as long as I don't get header errors?  (So far it's working fine.  I haven't had any errors using it.)"

It is perfectly fine :)


4) On a scale of 1 to 10, how secure would this be, "as-is," for preventing someone from getting to either "test.php" or "test2.php" outside of a valid login?  The most sensitive data that could be accessed in the whole application would be name, address and phone numbers.  No SSNs, financial account numbers, etc.

I would actually say 10, or 9, because the data is not that sensitive, so the only thing trying to get that kind of data would be robots (as in crawlers) and if they hit a login system, they just go elseware, unless they can register, but since in the registration script you have to validate their email address, they move on.

-------

On to your second post, now I assume you are trying to diplay data from a table so replace the code you gave me with this:

$sql="SELECT * FROM $table WHERE $UserFieldName='$username' AND $PasswordFieldName='$password'"; // SQL to check if the user exsists
$result=mysql_query($sql); // Perform the MySQL query
$result = mysql_num_rows($result);  // See if it exsists

if($result !=="0")
        { // If it does exsist
            $_SESSION["password"] = $password; // Register the password to the session
            $_SESSION["username"] = $username; // Register the username to the session
            $_SESSION["loggedin"] = true;
            
                  while($rows=mysql_fetch_array($result)){ // Now you need to ask for the data
                        $_SESSION["id"] = $rows['ID']; // Register the key field to the session
                  }
            
            header("Location: test.php");
}

-----

Now your last post, you say they both prove the same thing, in the script above I have changed it to:
if($result !=="0")
That just means, if $result is not 0.
If you still get errors, that the header function away and put:
echo mysql_error();
and see what happens.

- Adam
StateGuy

ASKER
Oh... so technically $row['ID'] is inaccessible until you do a "mysql_fetch_array."  So can I assume I could load multiple session variables from this one "mysql_fetch_array", provided the query called everything (select * from...)?

I also took your advice and used a java redirect:
<script type="text/javascript">
     window.location = "AAPCSCSTab1.php"
</script>

instead of:
     header("Location: test.php");

It works very well.  Shoot, I might actually become a real programmer yet.  I'll let you know ASAP how it goes.  Thanks again.  BTW, did you make that change on your website so I can use my email address to register?

Randy
Ludatha

Remember, programming is like teaching a baby how to speak, you have to tell it everything!
I want to be a proper programmer, I'm only 15 years old so I've got a long way to go yet :D

And yes I have made the change to the website, although please note that ludatha.com is a work in progress and is half done (it's like alpha-alpha :P)

So I wish you good luck on your programming, and if you want to gain some skills, download an open source application and try and understand how it works, I looked at e107 for about 2 hours, then I was like an expert at it :)
Maby I'll hire you some day haha :D
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
StateGuy

ASKER
OK, dude.  Below are the four files that work just like I wanted them to, thanks to you.  If you test them and they work for you as well, send a message back confirming that fact and I'll select it as the solution and stick you with 500 points.

I appreciate everything you've done, plus the time you've spent.  15, huh?  Don't look to hire anyone.  Look for a small company that needs help and have them hire you.  That way you don't have to worry about payroll, payroll taxes, medical and dental benefits, etc.  Sit back and cash the checks.  Better yet, at your age, be a contractor; pick and choose assignments that interest you and KEEP BACKUPS OF EVERYTHING!!!  You'll thank me later.  Here's the code for those four files in the snippet window.  It doesn't look like much, but it works.  And like WWE's Stone Cold Steve Austin says, "and that's the bottom line!"

Randy


<?php
 
/***************/
/*  login.php  */
/***************/
 
session_start();
 
function login($username,$password)
    {   
        require_once("includes/DbVars.php");
 
        mysql_connect("$host", "$mysql_user", "$mysql_pass") or die ("Query failed: " . mysql_error());
        mysql_select_db("$database") or die ("Cannot select DB: " . mysql_error());
 
        $password = md5($password); // Encrypt the password from the form
        $sql = "SELECT * FROM $table WHERE $UserFieldName='$username' AND $PasswordFieldName='$password'";
        $result = mysql_query($sql);
        # Using "$result" in the line above AND below caused an error. Using "$dataset" cured it.
        $dataset = mysql_num_rows($result);  
 
        if ($dataset != "0")
            {
                $row = mysql_fetch_row($result);
                $_SESSION["key"] = $row[0];
				
                $_SESSION["password"] = $password;
                $_SESSION["username"] = $username;
                $_SESSION["loggedin"] = true;
				
                ?>
 
                <script type="text/javascript">
                    window.location = "test.php"
                </script>
 
                <?php
				
            }
        else
            {
                session_destroy();
                echo "Wrong username or password. Please try again!";
            }
        	
    } // End of function
 
if(isset($_GET["submit"]))
	{
        $user = $_POST['username'];
        $pass = $_POST['password'];
        
        login($user, $pass);
	}
 
?>
 
<br>Please Login<br/>
 
<!-- Now for the form -->
<form method="post" action="login.php?submit"> 
    Username&nbsp;<input type="text" name="username" id="username"/><br/>
    Password&nbsp;<input type="password" name="password" id="password"/><br><br/>
    <input type="submit" value="Login"/>
</form>
 
//////////////////////////////////////
 
<?php
 
/**************/
/*  test.php  */
/**************/
 
session_start();
 
if ($_SESSION["loggedin"] != true) 
    {
        ?>
        <script type="text/javascript">
            window.location = "login.php"
        </script>
        <?php
    }
else 
    {
        echo "You are Logged In, page 1!"; ?> <br/> <?php
        echo "key = " . $_SESSION["key"]; ?> <br/> <?php
    }
 
?>
 
<!-- Page to be accessed only by valid login -->
 
<form method="post" action="test2.php"> 
    <input type="submit" value="Page 2"/>
</form>	
	
<form method="post" action="logout.php"> 
    <input type="submit" value="Logout"/>
</form>	
 
//////////////////////////////////////
 
<?php
 
/***************/
/*  test2.php  */
/***************/
 
session_start();
 
if ($_SESSION["loggedin"] != true) 
    {
        ?>
        <script type="text/javascript">
            window.location = "login.php"
        </script>
        <?php
    }
else 
    {
        echo "You are Logged In, page 2!"; ?> <br/> <?php
        echo "key = " . $_SESSION["key"]; ?> <br/> <?php
    }
 
?>
 
<!-- Page to be accessed only by valid login -->
 
<form method="post" action="test.php"> 
    <input type="submit" value="Page 1"/>
</form>	
 
<form method="post" action="logout.php"> 
    <input type="submit" value="Logout"/>
</form>	
 
//////////////////////////////////////
 
<?php
 
/****************/
/*  logout.php  */
/****************/
 
session_start();
session_destroy();
 
?>
 
<script type="text/javascript">
    window.location = "login.php"
</script>

Open in new window

ASKER CERTIFIED SOLUTION
Ludatha

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
StateGuy

ASKER
The actual code is in the snippet window above in my request for verification.  It may have been an easy question for many, which may be why no one by Ludatha answered it, but it was worth the 500 points to me.

Randy
StateGuy

ASKER
Adam,

Did you get the 500 points?  I don't see where it was awarded.

Randy
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
Ludatha

Thanks, I got 500 points, and since you gave me a grade A I got 2000 points instead :D
StateGuy

ASKER
ooooooooo... 2K, huh?  Well, congrats and I'm glad it worked out well for you because I like what I got out of it. I've got three points left but a smile on my face!  Thanks again.