Home > Mobile >  (PHP)Login Only Gets Redirected To 1 Page
(PHP)Login Only Gets Redirected To 1 Page

Time:01-10

My admin page is The only one being accessed for both.

my Code: <?php

  if ($_SERVER[ 'REQUEST_METHOD' ] == 'POST')
  {
  $usernane = $_POST['username'];
  $password = sha1($_POST['password' ]);
  $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1");
  $stmt->execute(array($usernane, $password));
  $checkuser = $stmt->rowCount();
  $user = $stmt->fetch();

When Ever I log into my User page it gets redirected to the Admin Page.

When I try to adjust the code most of the time only 1 page works.

Any help will be appreciated!

  if ($checkuser === 0)
  {
  $_SESSION[ 'user' ] = $user['username'];
  $_SESSION[ 'type'] = $user['type'];
  header('location:User.php');

  }if ($checkuser === 1)
  {
  $_SESSION[ 'user' ] = $user['username'];
  $_SESSION[ 'type'] = $user['type'];
  header('location:Admin.php');

  }
  }
  ?>

CodePudding user response:

In the second part of your code you are checking whether the user exists or not, if you want to seperate admins from normal users, you need to check the usertype instead of row count:

/*----- Check User Exists? ------*/
    if ($checkuser === 0){
        // This area will execute when user not exists.
    }else if($checkuser === 1){ // I suggest to add 'else' in here 

        /*----- Get user Data ------*/
            $_SESSION[ 'user' ] = $user['username'];
            $_SESSION[ 'type'] = $user['type'];

    /*----- Check Privilage In here ------*/
        if($user['type'] == 1){ // If your admin type == 1 then use it else change '1' in here
            header('location:Admin.php');
        }else{
            header('location:User.php');
        }

    }

CodePudding user response:

I hope this will help you:

  1. Rearrange your user table:
    USER:
      -> id (int)
      -> username (string)
      -> password (string)
      -> isAdmin (bool)
  1. fire your Request:
    $usernane = $_POST['username'];
    $password = sha1($_POST['password' ]);
    $stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1");
    $stmt->execute(array($usernane, $password));
  1. check the result
    if($stmt->rowCount() > 0) {
      $user = $stmt->fetch();
      if($user['isAdmin'])
      {
        $target = 'Admin.php';
      } else {
        $target = 'User.php';
      }
      header(sprintf('location:%s', $target));
      
    } else {
      // no user found with this credentials
    }

Be careful, I have not tested the code.

Next you have todo: never save clear passwords to the database. Take a look on the password tools of php and use that.

https://www.php.net/manual/de/function.password-hash.php

  •  Tags:  
  • Related