Authenticating user in PHP

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tdrsam
    New Member
    • May 2015
    • 97

    Authenticating user in PHP

    I have a login page for an admin area and I want to keep people from being able to access pages if they're not logged in.

    This is the script that logs the user in;

    Code:
    <?php
    session_start();
    include ('includes/DbCon.php');
    
    // username and password sent from form 
    $user=$mysqli->real_escape_string($_POST['user']);
    $password=$mysqli->real_escape_string($_POST['password']);
    
    $sql="SELECT * FROM xyz WHERE user='$user' and password='$password'";
    $result=$mysqli->query($sql);
    
    // Mysqli_num_rows is counting table rows
    if(mysqli_num_rows($result) == 1){
    $row = mysqli_fetch_array($result, MYSQLI_BOTH);
    
    // Register $user, $password and redirect to admin area
    
    $_SESSION['user']=="user";
    $_SESSION['password']=="password";
    
    echo '<script type="text/javascript">';
    echo 'document.location.href = "/pc.v.2/admin.php";';
    echo '</script>';
    
    }
    else {
    echo '<script type="text/javascript">';
    echo 'alert("Invalid Username or Password");';
    echo 'history.back();';
    echo '</script>';
    
    }
    mysqli_close($mysqli);
    ?>

    And this is how I'm trying to authenticate the login;

    Code:
    <?php
    session_start();
    if (empty($_SESSION['user'])){
    header("location:login.php");
    }
    else{
    echo '<script type="text/javascript">document.getElementsByClassName("login").innerHTML="Logout";';
    echo 'document.location.href = "/pc.v.2/admin.php";'; 
    echo "</script>";
    }
    ?>

    But it redirects back to the login page when the correct username and password are entered. There's something wrong with the script that checks the session, isn't there?
  • Rabbit
    Recognized Expert MVP
    • Jan 2007
    • 12517

    #2
    You never set your session variables. 2 equal signs is a comparison operator, 1 equal sign is the assignment operator.

    Comment

    • tdrsam
      New Member
      • May 2015
      • 97

      #3
      Thanks. I also had a redirect in the authentication script that was causing a constant reloading of the page.

      Comment

      Working...