2

I have built a login php form for an internal website I'm building for our intranet. I am going to combine a few different websites together under one login system. I want to see how I could check if a user is logged in if they visit one of the url's directly and if they're not logged in then redirect them to the login page then after successfully logging in redirect back to the initial page.

I have logged their username and password into a cookie. I know this isn't secure, but again this is just an in house website on the companies intranet. So I don't need much security. The log in system is to just track what each user is doing.

Here's my login code, but now I need to figure out how to check if a user is logged in or not on separate web pages.

//get info from login form
if(isset($_POST['login'])) {

$username = $_POST['username'];
$password = $_POST['password'];
$rememberme = $_POST['rememberme'];

$username = mysqli_real_escape_string($connection, $username);
$password = mysqli_real_escape_string($connection, $password);
//query users table
$query = "SELECT * FROM users WHERE username = '{$username}' ";
$select_user_query = mysqli_query($connection, $query);

if(!$select_user_query) {

    die("Query failed" . mysqli_error($connection));

}
//loop through user info and assigning to variables
while($row = mysqli_fetch_array($select_user_query)) {

    $db_id = $row['user_id'];
    $db_username = $row['username'];
    $db_password = $row['user_password'];
    $db_firstname = $row['user_firstname'];
    $db_lastname = $row['user_lastname'];
    $db_role = $row['user_role'];

}

//validate username and password
if($username === $db_username && $password === $db_password) {
    //create cookie to remember user
    if(isset($rememberme)) {
        //set cookie to last one year
        setcookie('username', $_POST['username'], time()+60*60*24*365, '/', 'localhost');
        setcookie('password', md5($_POST['user_password']), time()+60*60*24*365, '/', 'localhost');
    } else {
        //cookie expires when browser closes
        setcookie('username', $_POST['username'], false, '/', 'localhost');
        setcookie('password', md5($_POST['user_password']), false, '/', 'localhost');   
    }

    //if user exists send to dashboard
    $_SESSION['username'] = $db_username;
    $_SESSION['user_firstname'] = $db_firstname;
    $_SESSION['user_lastname'] = $db_lastname;
    $_SESSION['user_role'] = $db_role;

    header("Location: ../dashboard.php ");

} else {

    header("Location: ../index.php");

}

}
JBaldwin
  • 354
  • 1
  • 3
  • 19
  • 1
    you can make a ajax call with the user id every 2 or more minutes. save the users in a text file. If the ajax stop then you know that the user is not active anymore – Rafael Shkembi Jan 10 '17 at 14:38
  • @Roljhon how could I do it with the db? I'm still a little new to PHP and mysql – JBaldwin Jan 10 '17 at 14:41
  • 1
    Look through this question and see if it answers your question. I'm not sure if it's 100% what you want to do but it might be close. http://stackoverflow.com/questions/31031344/php-how-to-check-if-user-is-already-logged-in-and-otherwise-redirect-to-login-p – lostInTheTetons Jan 10 '17 at 14:41
  • 2
    You can just add something like `$_SESSION['logedIn'] = true;` to the cookies when the user succesfully logs in. And check on every page if he is loged in. – WasteD Jan 10 '17 at 14:42
  • 3
    you use a hash to store the password in your cookie - which you don't even need to do (plus: MD5 has been insecure for years, don't use it). but it seems you store it plain-text in your database - **which you should never do** - use `password_hash()` to create a **secure** hash, insert that in your DB and check passwords with `password_verify()` – Franz Gleichmann Jan 10 '17 at 14:43
  • 1
    You are open to [SQL Injections](http://php.net/manual/en/security.database.sql-injection.php) and should really use [Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead of concatenating your queries. `mysqli_real_escape_string()` will never be as secure as Prepared Statements, since it still relies on concatenating the values with the query. More importantly, follow @FranzGleichmann advice regarding password hashing. – M. Eriksson Jan 10 '17 at 14:48
  • @JBaldwin you do it with sessions since it's only the company which is using the site. – Roljhon Jan 10 '17 at 14:51
  • Any chance once the user logs in to direct them back to that specific page they were trying to visit? – JBaldwin Jan 10 '17 at 15:06

2 Answers2

3

Here is how to check if a user is logged in and then redirect them to the page they first visited.

First check to see if a user is logged in:

<?php

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

?>

Then include that file in all of your web pages you will be using. Also, create a session for the URL. This will go at the top of your page:

<?php include "includes/login-check.php"; ?>
<?php $_SESSION['url'] = $_SERVER['REQUEST_URI']; ?>
<?php ob_start(); ?>

Then right in the body of the HTML add this:

<input type="hidden" name="redirurl" value="<? echo $_SERVER['HTTP_REFERER']; ?>" />

Then within your login file check for the URL session:

    //check to see what page user first visited
    if(isset($_SESSION['url'])) {
        $url = $_SESSION['url'];
    } else {
        $url = "../index.php";
    }
    //redirect user to page they initially visited
    header("Location: $url");

That should fully answer your question.

lostInTheTetons
  • 1,162
  • 1
  • 13
  • 23
2

Create a file which you should include at the top in every file of your system and add the following code

session_start();
if(!(isset($_SESSION['username'])))
{
    header("Location:login.php")
}
coder
  • 906
  • 1
  • 12
  • 19