Page 1 of 1

How to go about making sure a user has logged in

Posted: Sun Apr 19, 2009 8:44 pm
by xplore
I've made a few additions to my site that I would like only a few people to see / use. I'm using a static log-in until I learn SQL and generally get better with PHP. The code in the first window below is just a login form that checks to see if the user has entered the correct information if so ' $_SESSION['valid'] = true; '. I use this session variable in my other page called loggedin.php to see if it is false then header("Location: login.php"); But nothing is working because i can enter in anything and it will just show me that page. I can also just go to the page I wish the user not to see until they log in even though $_SESSION['valid'] = false;

Please help or possibly just lead me to the right way to handle logging in or keeping track of that kind of stuff.

Code: Select all

<?php
 
session_start();
 
// variable used to tell whether user logged in with correct info
$_SESSION['valid'] = false;
 
//var
$bool1 = false;
$bool2 = false;
$pass_error = false;
$user_error = false;
 
if (isset($_POST['username']) && isset($_POST['password'])) {
    // user entered something
    if ($_POST['username'] = "admin") {
        // username correct
        $bool1 = true;
    }
    else {
        $user_error = true;
    }
    
    if ($_POST['password'] = "password") {
        // password correct
        $bool2 = true;
    }
    else {
        $pass_error = true;
    }
    
    if ($bool1 = true && $bool2 = true) {
        // both username / password correct - redirect
        $_SESSION['valid'] = true;
        header("Location: loggedin.php");
    } 
    else {
        echo "login.php"; 
    }
}
else {
    // user hasn't entered anything
    ?>
    <h1 align="middle">Login</h1> <?php
}
?>
 
<html>
<body>
<form method="post" action="<?php echo "login.php"; ?>">
 
<table border="1" align="center">
<tr><td>Username: </td><td><input type="text" name="username" /></td></tr>
<tr><td>Password: </td><td><input type="text" name="password" /></td></tr>
<tr><td><input type="submit" value="login" /></td></tr>
 
</form>
<?php
 
if ($pass_error) {
// if true user has entered wrong pass
echo "/n/n wrong password /n";
}
 
if ($user_error) {
// if true user has entered wrong user
echo "/n/n wrong username /n";
}
 
?>
 
 
</table>
</body>
</html>

Code: Select all

<?php
 
session_start();
 
if ($_SESSION['valid'] = true) {
    // user should be here 
    echo "<h1>Welcome user " . session_id() . "</h1>";  
}
else {
    // redirect because user has not logged in 
        
}
 
 
?>

Re: How to go about making sure a user has logged in

Posted: Sun Apr 19, 2009 10:58 pm
by mischievous
Hey I included some code that is for my login system ... prob could be refined a bit but should get you going... its running from a database but could easily be converted to a static login. It also is setup with sha1 encryption and is setup to be anti-code-injection.... hehe... let me know if you have any questions etc.

Code: Select all

<?
/*
I have all my login information in external class file 
but you could include it! This is also with a database 
driven login... which you said you didnt want... but its
really simple to setup. so here it is... 
*/
//database connect
function GetMyConnection($command){
       //database config
      $DB_SERVER = "localhost";
      $DB_SERVER_USERNAME = "username";
      $DB_SERVER_PASSWORD = "password";
      $DB_DATABASE = "databasename";
 
      $DB_LINK = mysql_connect($DB_SERVER, $DB_SERVER_USERNAME, $DB_SERVER_PASSWORD);
      if ($command != "open"){
          mysql_close($DB_LINK);
      } else {
          mysql_select_db($DB_DATABASE, $DB_LINK) or die('Could not select database.');
          //echo("Connected To ".$DB_DATABASE);
          return $DB_LINK;
      }
}
//run check with database and logs user in
function accountLogin($username, $password){
        GetMyConnection('open');
        $ecrypted_pass = sha1($password);
        $result = mysql_query("SELECT * FROM users WHERE username = '".$username."'");
        $check = mysql_num_rows($result);
        if($check == 0){
        } else {
            while($row = mysql_fetch_array($result)){
                if($row['password'] == $ecrypted_pass){
                    setcookie("userStatus","logged-in", time()+2592000);
                } else {
                    echo("<h1>You have entered an incorrect Password</h1>");
                }
            }
        }
        GetMyConnection('close');
}
//checking to see if fields have been posted 
if((isset($_POST["username"])) && (isset($_POST["password"])){
    //grab userinfo
    $username = $_POST["username"];
    $password = $_POST["password"];
    //quick clean up
    $badchars = array("\"", "\\", "/", "*", "'", "=", "-", "#", ";", "<", ">", "+", "%");
    $cleanusername = str_replace($badchars, "", $username)
    $cleanpassword = str_replace($badchars, "", $password)
    //run login function
    accountLogin($cleanusername, $cleanpassword)
}
 
if(isset($_COOKIE['userStatus'])){
} else {
    header('Location: signin.php' ) ;
}
?>
 
Hope this helps... could make a non db script for ya... but would have to wait till tomorrow

Re: How to go about making sure a user has logged in

Posted: Sun Apr 19, 2009 11:01 pm
by califdon
xplore wrote:

Code: Select all

if ($_SESSION['valid'] = true) {
>
Your problem is right there. The = operator assigns a value to the variable on the left. You need the comparison operator, ==.

Re: How to go about making sure a user has logged in

Posted: Mon Apr 20, 2009 12:30 am
by MasterBeta
Your code seems a little unnecessarily hectic.
Use this as your log in form. You should only need to change lines 4 - 7 to get it working.

login.php

Code: Select all

<?php
session_start();
### BEGIN CONFIGURATION ###
$staticUsername = 'admin'; // set the username
$staticPassword = 'password'; // set the password
$loginErrorMsg = "Incorrect Login"; // the error message for incorrect login
$secretPage = "loggedin.php"; // your secret page. directory can be added (ex. $secretPage = "/admin/login.php")
### END CONFIGURATION ###
 
### BEGIN CODE ###
$error = FALSE; // set error to FALSE by default
if($_POST['username'] != $staticUsername) $error = TRUE ; // if the username is incorrect set $error to TRUE
if($_POST['password'] != $staticPassword) $error = TRUE ; // if the password is incorrect set $error to TRUE
if(!$error) $_SESSION['logIn'] = TRUE; // if there are no errors set $_SESSION['logedin'] to TRUE
else $_SESSION['logIn'] = FALSE; // otherwise set to FALSE
 
if($_SESSION['logIn']) header("Location:$secretPage"); // successful login - redirect to secret page
else if(isset($_POST['username'])) $showError = TRUE;  // unsuccessful login - show error
### END OF CODE ##
?>
<html>
<body>
<form action="<?php print $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="logIn" id="logIn">
  <table border="1" align="center">
    <?php
    if($showError) print "<tr><td colspan=\"2\">$loginErrorMsg</td></tr>";
    ?>
    <tr>
      <td>Username: </td>
      <td><input type="text" name="username" /></td>
    </tr>
    <tr>
      <td>Password: </td>
      <td><input type="text" name="password" /></td>
    </tr>
    <tr>
      <td colspan="2"><input type="submit" value="login" /></td>
    </tr>
  </table>
</form>
</body>
</html>
Change line 3 to the location of your login form and add the first 5 lines to each page you wish to protect. Make sure they are at the very beginning of each page!
Also, you can log out by setting logout=TRUE. Here's an example by simply using a logout URL ?logout=TRUE
loggedin.php

Code: Select all

<?php
session_start();
if($_REQUEST['logout'] == "TRUE") unset($_SESSION['logIn']);
if(!$_SESSION['logIn']) header("Location:login.php");
?>
<html>
<head>
<title>Secret Page</title>
</head>
<body>
<p>If you can see this secret page you must be logged in.</p>
<p><a href="?logout=TRUE">log out</a></p>
</body>
</html>

Re: How to go about making sure a user has logged in

Posted: Wed Apr 22, 2009 9:08 pm
by mischievous
Yeah... the code isnt very organized as i was cutting and pasting from several classes i have setup from an application i am building :( sorry