3

I'm working on a login screen for a College project. Right now I have these two files.

index.php

<html>

<head>  
    <meta charset = 'UTF-8'>
    <link rel="shortcut icon" href="images/favicon.ico"/>           
    <title>Sistema de Estágios - UFMS - Login</title>
    <link href = "css/bootstrap.css" rel = "stylesheet" >
    <link href = "css/index.css" rel = "stylesheet" >
    <script src="js/jquery-1.11.1.min.js"></script>

    <?php
    session_start(); // start session

    if(isset($_SESSION["sessioname"]))
    {
        if($_SESSION["session_time"] >= time()) //time hasn't expired
        {
            $_SESSION["session_time"] = time() + 60;
            header("Location:users.php"); /* Redirect browser */
            exit();
        }
    }

    ?>

    <script type="text/javascript">
        $(document).ready(function()
        {
            $("input").blur(function() // This makes the container's border turn red when it is empty 
            {
                if($(this).val() == "")
                {
                    $(this).css({"border" : "1px solid #F00"});
                }
            });

            $("#botao").click(function()
            {
                var cont = 0;
                $("#form input").each(function()
                {
                    if($(this).val() == "")
                    {
                        $(this).css({"border" : "1px solid #F00"});
                        cont++;
                    }   
                });

                if(cont == 0)
                {
                    $("#form").submit();
                }
            });
        });
    </script>

</head>

<body>
<center>
    <center>
        <div class = "container">   
            <div class = "principal"> 
                    <form id="form" name="form" method="post" action="entra.php">
                        <p>
                            <label for="a">Nome de Usuário:</label>
                            <input id="a" type  ="text" name="username" class="form-control"/><br/>
                            <label id="name_null" hidden="hidden">O campo deve ser preenchido</label>
                        </p>
                        <p>
                            <label for="b">Password:</label>
                            <input id="b" type="password" name="password" class="form-control"/><br/>
                            <label id="pass_null" hidden="hidden">O campo deve ser preenchido</label>
                        </p>
                            <buttom id="botao" name="Entrar" value="login" class="btn btn-primary" style="width: 100%;">Login</buttom>
                    </form>
                <label> <a href="register.php"><button class="btn">Cadastre-se</button></a> </label>

            </div>
        </div>
    </center>
</center>

</body>

entra.php

<html>
<head>
    <script src="js/jquery-1.11.1.min.js"></script>
</head>

<?php
require_once "config.php"; // include conection to database
$mysqli = new mysqli("localhost", "root", "", "sistema");

// verify if there is a person with the recived name
$Tipo = $_POST['tipo'];

$user_info = mysqli_query($mysqli,"SELECT * FROM users WHERE username='".addslashes($_POST['username'])."'");

if(mysqli_num_rows($user_info) != 0)
{
    $result = mysqli_fetch_array($user_info); // put the informations in an array
    if($result['password'] == sha1($_POST['password']))// if the password matches
    {
        session_start(); // começa a seesion
        header("Cache-control: private");
        $_SESSION["sessioname"] = $_POST['username'];
        $_SESSION["auto"] = $result["Tipo"];
        $_SESSION["id"]= $result["id"];
        $_SESSION["session_time"] = time() + 60;// expiration timne
        header("Location: users.php");
        die();
    }
    else
    { // else show an alert
        ?>
        <script type="text/javascript">
            alert("Senha incorreta");
        </script>
        <?php

        header("Location: index.php");
        die(); 
    }
}
header("Location: index.php");
?>

I'm looking for a way to make the login actions happen on index.php instead of entra.php. I'm also looking for a better way to manage the session expire time. Something like a global variable so I don't have to change it on every single file whenever I want to change it for tests.

I'm pretty new with PHP so I would love to receive some help from you guys.

Victor
  • 319
  • 2
  • 10
  • 1
    `addslashes` is insecure. `sha1` is not the best encryption. Your professor will be mad. – Shahar Jan 13 '15 at 17:47
  • 3
    `session_start()` needs to be run before anything is sent to the browser. Put that in a PHP block at the top of your HTML file before any PHP. – Ding Jan 13 '15 at 17:48
  • 2
    addslashes is about as useful for preventing sql injection attacks as a wet kleenex is in drying up a swimming pool. As for the session expiry: Just set it in php. PHP will auto-clean stale sessions automatically. You just have to provide a max lifetime value. – Marc B Jan 13 '15 at 17:49
  • I've been discussing the security question with my other friends that are also on the project. They think it's unecessary for the aplication. But I intende to take care of some of those security issues later on the project – Victor Jan 13 '15 at 17:51
  • Since this is a college project it may not matter, but if you're handling the password security yourself you should read ["Salted Password Hashing"](https://crackstation.net/hashing-security.htm) to understand the issues at stake. – Stephen P Jan 13 '15 at 20:26
  • I'll do that. Thanks. – Victor Jan 14 '15 at 03:55

2 Answers2

1

Just move your entra.php code to index.php file and change the form's Post action to index.php as

<form id="form" name="form" method="post" action="index.php">

SESSION: first, start the session using session_start() andstore the last time the user made a request

<?php
  $_SESSION['timeout'] = time();
?>

in subsequent request, check how long ago they made their previous request (10 minutes in this example)

<?php
  if ($_SESSION['timeout'] + 10 * 60 < time()) {
     // session timed out
  } else {
     // session ok
  }
?>

The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request.

Tushar Gupta
  • 15,504
  • 1
  • 29
  • 47
1

A good way to generally manage settings is to add a file like config.php and have all of them stored there. Since you already have it, you can store everything in it.

$_CONFIG["SESSION_EXPIRATION_TIME"] = 86400;

Then you can require_once it or include it in a lib class. The good thing about the config file and not doing define("VAR", [val]) is that you can modify the variables if you need to have a custom config (say you have a test server and a production one and have different databases associated with them - you can easily override $_CONFIG. You can't do a lot about define).

Also, something a little harder (but useful) is to have a general file called index.php and include all other php files there (somewhat separating the logic from the view (html code)).

Also, do mysqli_real_escape_string to prevent SQL injections on the username.

As a general rule, it'd be a good idea to put the logic in a separate file and include it, instead of inlining it in the HTML.

If you want it to be one file, you can always check if the user's already logged and if your variables exist. Something along the lines of.

if(isset($_SESSION["sessioname"]) && $_POST['password'] !== NULL) {
    //login code
}

Then change action='entra.php' to action='index.php' (alternatively, but not preferably, omit it altogether).

Of course, you can always add a hidden input field with some value if the above makes you squint :)

Oh, and always do an exit() after you do header('...'). php - Should I call exit() after calling Location: header?

I hope that helps!

Community
  • 1
  • 1
  • It helped. I'm going to do some changes and the advice of leaving it on separated files will be taken. – Victor Jan 13 '15 at 18:17