Search code examples
phpmysqlsecurityauthenticationaudit-trail

How can I keep a log of users logging in and out?


I am creating an admin panel to log breakdowns, save tasks, log errors and much more. I currently have the following piece of code at the top of the screen which checks if a user is logged in, if not they are sent to the login / create a user page.

<?php
session_start();

        include 'login/config.php';

        if(!isset($_SESSION['username'])){
            header('location:login/index.php');
            exit();
        }


?>

I feel that there may be better ways of doing this and also more secure ways. A username and password are required to login and get to the initial dashboard and user status levels & permissions will be added later on.

QUESTIONS::

How can I make the system more secure by improving the code or adding additional security features?

AND

How can I log to my SQL database when a user logs in and out of the admin system?


Solution

  • As for security, I'm no expert there, so I'll rather wait and see what the other people tell you, since it's a very interesting topic. But I'll give you my thoughts anyway.

    First of all, you should take care of SQL injections on your login, always validate the input data from the users, specially on CRUD operations. I think protecting your pages with sessions should be good enough, as long as the login itself is secure, for example you could implement a system that would block the IP after few failed attempts to login etc...

    About the second part, you can create a table i.e. userlog which would contain the fields you want, user_id, action(login/logout), time. Then everytime the user does login/logout, you just insert a new record to the table. That piece of code would be located where you set/unset the session. Not sure about the efficiency of this method, but this is a way to implement what you are saying.