Correct login screen using PHP and Javascript

I am working on a login screen for a college project. I have these two files right now.

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 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 login actions on index.php

instead entra.php

. I am also looking for a better way to manage the session expiration time. Something like a global variable so I don't have to change it every single file when I want to change it for tests.

I am new to PHP so would like some help from you guys.

+3


source to share


2 answers


Just move the code entra.php

to file index.php

and change the form Post action

to index.php

like

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

      

SESSION: first start a session using session_start()

and save the last time the user made a request

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

      



in the next 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 your own session timeout. Use a simple timestamp that marks the time of the last activity (i.e. Request) and updates it with each request.

+1


source


A good way to manage the settings is to add a file such as config.php

, and they are all stored there. Since you already have it, you can store everything in it.

$_CONFIG["SESSION_EXPIRATION_TIME"] = 86400;

      

Then you can require_once

or include it in the lib class. The good thing about the config file and not doing define("VAR", [val])

is that you can change the variables if you need to have a custom config (say you have a test server and a production server and they have different databases associated with them - you can easily override $_CONFIG

. You can't do much about define

).

Also, something a little trickier (but useful) is to have a common file named index.php

and include all other php files in it (separating logic from view (html code) somewhat).

Also, do mysqli_real_escape_string

to prevent SQL injection into username.

Generally, it would be nice to put the logic in a separate file and include it instead of embedding it in the HTML.



If you want it to be one file, you can always check if the user was already logged in and if your variables exist. Something like lines.

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

      

Then change action='entra.php'

to action='index.php'

(alternatively, but not desirable, omit it completely).

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

Oh, and always do exit()

after doing header('...')

. php - Should I call exit () after calling the Location header:

I hope this helps!

+1


source







All Articles