Jump to content

Admin check login just redirects back to login page


Go to solution Solved by ginerjm,

Recommended Posts

Hey All, I am new to php and I am trying to learn how to set up my admin where it checks to see if the user is logged in before they can access the rest of the admin page. Right now I have it working but the user can access the pages if they know the url.

 

I tried following a tutorial I found online but all it is doing is redirecting me back to the login page. It does the checklogin.php and it goes to the dashboard.php but redirects me as soon as I get there.

 

Can you please look at my code and let me know if I am missing something simple?

 

Any help would be very much appreciated.

 

My form

<form name="form1" method="post" action="checklogin.php">
    <div id="wrappermiddle">
    <h2>Login</h2>
                <div id="username_input"> 
                <div id="username_inputleft"></div>
                    <div id="username_inputmiddle">
                    <input name="myemail" type="text" id="myusername" placeholder="Email Address">
                    <img id="url_user" src="./images/mailicon.png" alt="">      
                    </div><!--ends username_inputmiddle-->
                    <div id="username_inputright"></div>                   
                </div><!--ends username_input-->


                <div id="password_input">
                <div id="password_inputleft"></div>
                    <div id="password_inputmiddle">       
                    <input name="mypassword" type="password" id="mypassword" placeholder="Password">
                    <img id="url_password" src="./images/passicon.png" alt="">        
                    </div><!--ends password_inputmiddle-->
                 <div id="password_inputright"></div>
                </div><!--ends password_input-->
    
            <div id="submit"> 
            <input type="image" src="./images/submit.png" name="Submit" value="Login">      
           </form>

 

checklogin.php

<?php
$host="localhost"; // Host name 
$username="db-username"; // Mysql username 
$password="db-password"; // Mysql password 
$db_name="db-name"; // Database name 
$tbl_name="members"; // Table name 


// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");


// username and password sent from form 


$myemail = "";
$mypassword = "";
$errorMessage = "";
$num_rows = 0;
$myemail=$_POST['myemail']; 
$mypassword=$_POST['mypassword']; 


// To protect MySQL injection (more detail about MySQL injection)
$myemail = stripslashes($myemail);
$mypassword = stripslashes($mypassword);
$myemail = mysql_real_escape_string($myemail);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE myemail='$email' and password='$mypassword'";
$result=mysql_query($sql);


if ($result) {


}
else {


$errorMessage = "Error logging on";


}


// Mysql_num_row is counting table row
$num_rows = mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if ($num_rows > 0) {
$errorMessage= "logged on ";
}
else {
$errorMessage= "Invalid Logon";
}


// Register $myusername, $mypassword and redirect to file "login_success.php"
if ($num_rows > 0) {


session_start();
$_SESSION['members'] = "1";
header ("Location: dashboard.php");


}
?>

Here is what I have at the top of dashboard.php

<?PHP
session_start();
if (!(isset($_SESSION['checklogin']) && $_SESSION['checklogin'] != '')) {
header ("Location: index.php");
}
?>

Also, so I don't have to ask again, I have my database set up that a user can be a superuser (role 1) or a regular user (role 2). How can I set it that based on what type of user they are, they get sent to 2 different urls?

 

I have learned so much from this site along with other forums but this one I haven't been able to figure out. Like I mentioned, I seen and followed a few tutorials but I couldn't get them working with my code I already had. So I figured this would be easier than having to redo my entire login page.

 

Thanks Again.

I edited the checklogin but now it is giving me a "Wrong username or password" I found a thread with the exact issue I was having but for some reason its not reading the db info.

 

<?php
ob_start();
$host="localhost"; // Host name 
$username="db-username"; // Mysql username 
$password="db-password"; // Mysql password 
$db_name="db-name"; // Database name 
$tbl_name="members"; // Table name 


// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");


// Define $myusername and $mypassword 
$myusername=$_POST['email']; 
$mypassword=$_POST['password']; 


// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM members WHERE email='$myusername' and password='$mypassword'";
$result=mysql_query($sql);


// Mysql_num_row is counting table row
$count=mysql_num_rows($result);


// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){


// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("email");
session_register("password"); 
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
ob_end_flush();
?>

That was an old tutorial you followed

 

Besides what I wrote below the main redirect issue is that you are checking for $_SESSION['checklogin'] in dashboard.php but never set the session or check a value anywhere else

session_start();
if (!isset($_SESSION['members']) || $_SESSION['members'] != "1") {
header ("Location: index.php");
}

mysql_* functions are deprecated and should use mysqli_* or pdo

session_register() deprecated, use $_SESSION['email'] = "me@mail.com";

you are passing plain text passwords and should be using something like password_hash() and to check the password is password_verify()

don't use stripslashes, only use the appropriate escape functions such as mysql_real_escape_string() , mysqli_real_escape_string() , or pdo prepared statements

trim the whitespace or can end up different values

 

You should find a new tutorial using pdo or mysqli

Appreciate your time and help, I have searched and searched for a mysqli tutorial and I cannot find anything good. Everything I am finding is about registering a member and not about the login. 

 

I am about to try this one and see if I can get it working.

https://www.2freehosting.com/forum/topic455-guide-php-mysqli-oop-simple-login-script.html

 

Appreciate your time and help, I have searched and searched for a mysqli tutorial and I cannot find anything good. Everything I am finding is about registering a member and not about the login. 

 

I am about to try this one and see if I can get it working.

https://www.2freehosting.com/forum/topic455-guide-php-mysqli-oop-simple-login-script.html

 

That's a better start, adding password encryption and your session data should work

Yea, guess that would help.

 

index.php

<?php
  session_start();
  include "includes/class.users.php";
  if(isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $users->login($username, $password);
  }
?>


<form method="POST" action="" name="login">
    <div id="wrappermiddle">
    <h2>Login</h2>
                <div id="username_input"> 
                <div id="username_inputleft"></div>
                    <div id="username_inputmiddle">
                    <input name="myemail" type="text" id="myusername" placeholder="Email Address">
                    <img id="url_user" src="./images/mailicon.png" alt="">      
                    </div><!--ends username_inputmiddle-->
                    <div id="username_inputright"></div>                   
                </div><!--ends username_input-->




                <div id="password_input">
                <div id="password_inputleft"></div>
                    <div id="password_inputmiddle">       
                    <input name="mypassword" type="password" id="mypassword" placeholder="Password">
                    <img id="url_password" src="./images/passicon.png" alt="">        
                    </div><!--ends password_inputmiddle-->
                 <div id="password_inputright"></div>
                </div><!--ends password_input-->
    
            <div id="submit"> 
            <input type="image" src="./images/submit.png" name="login" value="Login">      
           </form>

class.database.php

<?php


class Database {
  public function __construct() {
    $host = 'localhost';
    $user = 'admin';
    $pass = 'password';
    $name = 'database';
    $this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
  }
}


?>

class.users.php

<?php
   include "class.database.php";
  class Users extends Database {
    public function login($myemail, $mypassword) {
      $stmt = $this->mysqli->prepare("SELECT email, password FROM members WHERE email = ? AND password = ? LIMIT 1");
      $stmt->bind_param('ss', $myemail, $mypassword);
      $stmt->execute();
      $stmt->bind_result($myemail, $mypassword);
      $stmt->store_result();
      if($stmt->num_rows == 1) {
        while($stmt->fetch()) {
          $_SESSION['email'] == $myemail;
          header("Location: dashboard.php");
        }
      } else {
          return false;
      }
      $stmt->close();
      $stmt->free_result();
    }
  }
  $users = new users();
?>
  • Solution

My oop is pretty weak but aren't you specifying incorrect var names in your MySQli call? Don't you want

 

$this->mysqli = new mysqli($host, $user, $pass, $name)

 

since those are the vars you bothered to initialize?

THANK YOU

 

That worked like a charm, I guess the tutorial was wrong. Now I need to figure out the 2nd part of it. Getting the user to reach different sections based on their role.

 

I have my database set up that a user can be a superuser (role 1) or a regular user (role 2). How can I set it that based on what type of user they are, they get sent to 2 different urls?

Forgive me if I don't explain it right. I am very new to php/mysql and this is my first real attempt at it.

 

Basically if a user logs in they either go to the admin.php or superadmin.php.

 

I have them set up as roles ( 1 & 2 ) in the databases.

 

role 1 would go to admin.php

role 2 would go to superadmin.php

 

I think something like this could work. The only difference in the 2 user roles is the superadmin can edit the user info but the admin cannot, so if I can hide that tab in the menu that would be great.

<?php
if(loggedin()==true){
$user_id=$_SESSION['user_id'];
$log=$con->prepare("SELECT username,user_level FROM users WHERE user_id='$user_id'");
$log->execute;
$log->bind_result($username, $user_level,$user_id);
$log->store_result;
if($log->fetch()) //fetching the contents of the row
{
if($user_level=='a'){?>
<a href = 'index.php'>Home</a>
<a href = 'profile.php'>Profile</a>
<a href = 'admin.php'>Admin</a>
<a href = 'index.php'>Log Out</a>
<?php
}if($user_level=='m'){?>
<a href = 'index.php'>Home</a>
<a href = 'profile.php'>Profile</a>
<a href = 'index.php'>Log Out</a>
<?php
}
}?>

Now to find out how to handle sessions so someone who had the direct url cannot go to the page, it will redirect them to the login page. Finding some good tutorials so far, going to try them and see what happens.

Edited by laflair13

When you have a user level you then want to go to that specific page, correct? So - go there! Why the anchor tags?

 

You say you want to send the user to two different urls based on their role. Where is THAT code? Not in what you have posted so far.

Your English is confusing me. You seem to be saying that you have code to do these things, but now you say you don't. Let's try this: When you query the db to ascertain if the user is allowed to access your site include the role value/code in that query. If the query proves the login to be correct, you have the role so you can use it in an if statement to make your script go to the correct next page.

 

Try:

if ($role==1)
header("Location: role1.php");
elseif ($role==2)
header("Location: role2.php");
else
echo "Invalid role in db";
exit();

Sorry to keep posting but I broke it trying to change "username" to "email". I want to have them put in their emails and not their usernames. I don't see where I could have went wrong.

 

index.php

<?php
  session_start();
  include "includes/class.users.php";
  if(isset($_POST['login'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];
    $users->login($email, $password);
  }
?>


<form method="POST" action="" name="login">
    <div id="wrappermiddle">
    <h2>Login</h2>
                <div id="username_input"> 
                <div id="username_inputleft"></div>
                    <div id="username_inputmiddle">
                    <input name="email" type="text" id="myusername" placeholder="Enter Email">
                    <img id="url_user" src="./images/mailicon.png" alt="">      
                    </div><!--ends username_inputmiddle-->
                    <div id="username_inputright"></div>                   
                </div><!--ends username_input-->




                <div id="password_input">
                <div id="password_inputleft"></div>
                    <div id="password_inputmiddle">       
                    <input name="password" type="password" id="mypassword" placeholder="Password">
                    <img id="url_password" src="./images/passicon.png" alt="">        
                    </div><!--ends password_inputmiddle-->
                 <div id="password_inputright"></div>
                </div><!--ends password_input-->
    
            <div id="submit"> 
            <input type="image" src="./images/submit.png" name="login" value="Login">      
           </form>

class.users.php

<?php
  include "class.database.php";
  class Users extends Database {
    public function login($email, $password) {
      $stmt = $this->mysqli->prepare("SELECT email, password FROM members WHERE email = ? AND password = ? LIMIT 1");
      $stmt->bind_param('ss', $email, $password);
      $stmt->execute();
      $stmt->bind_result($email, $password);
      $stmt->store_result();
      if($stmt->num_rows == 1) {
        while($stmt->fetch()) {
          $_SESSION['email'] == $email;
          header("Location: dashboard.php");
 if ( !isset($_SESSION) ) session_start();
        }
      } else {
          return false;
      }
      $stmt->close();
      $stmt->free_result();
    }
  }
  $users = new users();
?>

I apologize if I am not explaining it right. 

 

When I login, it is just redirecting back to the login page. All I did was changed the variable from "username" to "email" 

 

For example, I changed this

<?php
  include "class.database.php";
  class Users extends Database {
    public function login($username, $password) {
      $stmt = $this->mysqli->prepare("SELECT username, password FROM members WHERE username = ? AND password = ? LIMIT 1");
      $stmt->bind_param('ss', $username, $password);
      $stmt->execute();
      $stmt->bind_result($username, $password);
      $stmt->store_result();
      if($stmt->num_rows == 1) {
        while($stmt->fetch()) {
          $_SESSION['username'] == $username;
          header("Location: dashboard.php");
 if ( !isset($_SESSION) ) session_start();
        }
      } else {
          return false;
      }
      $stmt->close();
      $stmt->free_result();
    }
  }
  $users = new users();
?>
to this
<?php
  include "class.database.php";
  class Users extends Database {
    public function login($email, $password) {
      $stmt = $this->mysqli->prepare("SELECT email, password FROM members WHERE email = ? AND password = ? LIMIT 1");
      $stmt->bind_param('ss', $email, $password);
      $stmt->execute();
      $stmt->bind_result($email, $password);
      $stmt->store_result();
      if($stmt->num_rows == 1) {
        while($stmt->fetch()) {
          $_SESSION['email'] == $email;
          header("Location: dashboard.php");
 if ( !isset($_SESSION) ) session_start();
        }
      } else {
          return false;
      }
      $stmt->close();
      $stmt->free_result();
    }
  }
  $users = new users();
?>

and on the login page , I changed this

<?php
  session_start();
  include "includes/class.users.php";
  if(isset($_POST['login'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];
    $users->login($username, $password);
  }
?>
<form method="POST" action="" name="login">
    <div id="wrappermiddle">
    <h2>Login</h2>
                <div id="username_input"> 
                <div id="username_inputleft"></div>
                    <div id="username_inputmiddle">
                    <input name="username" type="text" id="myusername" placeholder="Email Address">
                    <img id="url_user" src="./images/mailicon.png" alt="">      
                    </div><!--ends username_inputmiddle-->
                    <div id="username_inputright"></div>                   
                </div><!--ends username_input-->

                <div id="password_input">
                <div id="password_inputleft"></div>
                    <div id="password_inputmiddle">       
                    <input name="password" type="password" id="mypassword" placeholder="Password">
                    <img id="url_password" src="./images/passicon.png" alt="">        
                    </div><!--ends password_inputmiddle-->
                 <div id="password_inputright"></div>
                </div><!--ends password_input-->
    
            <div id="submit"> 
            <input type="image" src="./images/submit.png" name="login" value="Login">      
           </form>

to this

<?php
  session_start();
  include "includes/class.users.php";
  if(isset($_POST['login'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];
    $users->login($email, $password);
  }
?>
<form method="POST" action="" name="login">
    <div id="wrappermiddle">
    <h2>Login</h2>
                <div id="username_input"> 
                <div id="username_inputleft"></div>
                    <div id="username_inputmiddle">
                    <input name="email" type="text" id="myusername" placeholder="Enter Email">
                    <img id="url_user" src="./images/mailicon.png" alt="">      
                    </div><!--ends username_inputmiddle-->
                    <div id="username_inputright"></div>                   
                </div><!--ends username_input-->

               <div id="password_input">
                <div id="password_inputleft"></div>
                    <div id="password_inputmiddle">       
                    <input name="password" type="password" id="mypassword" placeholder="Password">
                    <img id="url_password" src="./images/passicon.png" alt="">        
                    </div><!--ends password_inputmiddle-->
                 <div id="password_inputright"></div>
                </div><!--ends password_input-->
    
            <div id="submit"> 
            <input type="image" src="./images/submit.png" name="login" value="Login">      
           </form>
Edited by laflair13

I'm not here to analyze your code for whatever you may have changed. Look at your code yourself and see what you changed and put it back and check that it works. Then make little changes and test them out as any good programmer would do until you get the results you desire.

 

Good luck.

Thats what I have been doing. It works when I have the initial code in there that uses "username" but when I change it to "email" it stops working. I know how to do trial and error, I just don't understand why it would stop working because I changed the variable.

You appreciate our attempts to help you but you can't seem to answer any of our questions. Why? I asked you five question and you didn't answer any of them. You just repeated the same message. Try debugging your code by displaying some values instead of doing the redirect. See what your code is seeing instead of just assuming or wondering why it operates the way it does.

 

That's how programmers think and do.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.