0

When I log in, I'm redirected to a page from my online status, past the preset time, I automatically get back offline. I wanted to change this script so that when I'm online, if someone tries to access my data, she is denied access and redirected to another page, such as google. How can I make these small changes? Thank you.

This is login page

    <?php 
    require_once("functions.php");
    require_once("db-const.php");
    session_start();
    if (logged_in() == true) {
        redirect_to("profile.php");
    }
?>
<html>
<head>
    <title>User Login Form </title>
</head>
<body>
<h1>User Login Form </h1>
<hr />
<!-- The HTML login form -->
    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
        Username: <input type="text" name="username" /><br />
        Password: <input type="password" name="password" /><br />
        Remember me: <input type="checkbox" name="remember" /><br />

        <input type="submit" name="submit" value="Login" />
        <a href="forgot.php">Forgot Password?</a>
        <a href="register.php">Register</a>
    </form>
<?php
if (isset($_POST['submit'])) {
    $username = $_POST['username'];
    $password = $_POST['password'];

    // processing remember me option and setting cookie with long expiry date
    if (isset($_POST['remember'])) {    
        session_set_cookie_params('604800'); //one week (value in seconds)
        session_regenerate_id(true);
    } 

    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    # check connection
    if ($mysqli->connect_errno) {
        echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
        exit();
    }

    $sql = "SELECT * from users WHERE username LIKE '{$username}' AND password LIKE '{$password}' LIMIT 1";
    $result = $mysqli->query($sql);

    if ($result->num_rows != 1) {
        echo "<p><b>Error:</b> Invalid username/password combination</p>";
    } else {
        // Authenticated, set session variables
        $user = $result->fetch_array();
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];

        // update status to online
        $timestamp = time();
        $sql = "UPDATE users SET status={$timestamp} WHERE id={$_SESSION['user_id']}";
        $result = $mysqli->query($sql);

        redirect_to("profile.php?id={$_SESSION['user_id']}");
        // do stuffs
    }
}

if(isset($_GET['msg'])) {
    echo "<p style='color:red;'>".$_GET['msg']."</p>";
}
?>  
<hr />
</body>
</html>

This is profile page

<?php 
require_once("functions.php");
require_once("db-const.php");
session_start();
if (logged_in() == false) {
    redirect_to("login.php");
} else {
?>


<html>
<head>
    <title>User Profile </title>
    <script src="script.js" type="text/javascript"></script><!-- put it on user area pages -->
</head>
<body>
<h1>User Profile </h1>
<hr />
<?php
    if (isset($_GET['id']) && $_GET['id'] != "") {
        $id = $_GET['id'];
    } else {
        $id = $_SESSION['user_id'];
    }

    ## connect mysql server
        $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        # check connection
        if ($mysqli->connect_errno) {
            echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
            exit();
        }
    ## query database
        # fetch data from mysql database
        $sql = "SELECT * FROM users WHERE id = {$id} LIMIT 1";

        if ($result = $mysqli->query($sql)) {
            $user = $result->fetch_array();
        } else {
            echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
            exit();
        }

        if ($result->num_rows == 1) {
            # calculating online status
            if (time() - $user['status'] <= (300)) { // 300 seconds = 5 minutes timeout
                $status = "Online";
            } else {
                $status = "Offline";
            }

            # echo the user profile data
            echo "<p>User ID: {$user['id']}</p>";
            echo "<p>Username: {$user['username']}</p>";
            echo "<p>Status: {$status}</p>";            
        } else { // 0 = invalid user id
            echo "<p><b>Error:</b> Invalid user ID.</p>";
        }
}

// showing the login & register or logout link
if (logged_in() == true) {
    echo '<a href="logout.php">Log Out</a>';
} else {
    echo '<a href="login.php">Login</a> | <a href="register.php">Register</a>';
}
?>
<hr />
</body>
</html>
George
  • 1
  • *"Prevent login if a user is already online"* - I don't quite get that. Should probably read as: *"Prevent login if anyone else besides me is already online"*. – Funk Forty Niner Apr 27 '17 at 17:15
  • hide the login button/link – Junius L Apr 27 '17 at 17:16
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Apr 27 '17 at 17:16
  • 1
    **Never store plain text passwords!** Please use ***PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html)*** to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). ***It is not necessary to [escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Apr 27 '17 at 17:16
  • 1
    If you want only a single session for each user. That is not a small change. – frz3993 Apr 27 '17 at 17:17
  • The script I want to use on a my site and I want to prevent a user from giving her login credentials to simultaneously access – George Apr 27 '17 at 17:21
  • 1
    You are expected to try to **write the code yourself**. After [**doing more research**](https://meta.stackoverflow.com/q/261592/1011527) if you have a problem **post what you've tried** with a **clear explanation of what isn't working** and provide [a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Read [How to Ask](http://stackoverflow.com/help/how-to-ask) a good question. Be sure to [take the tour](http://stackoverflow.com/tour) and read [this](https://meta.stackoverflow.com/q/347937/1011527). – Jay Blanchard Apr 27 '17 at 17:23
  • Don't use `LIKE` when selecting users, use `=`. Apart from opening you up to SQL injection, it is not going to be an indexed query, and will quickly degrade in performance as the number of users increases. – Alex Howansky Apr 27 '17 at 17:26
  • Talk about weird requirements – Rotimi Apr 27 '17 at 17:36

0 Answers0