1

So I have this code:

<?php
session_start();
if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} 
if(isset($_SESSION['count'])) {
  $_SESSION['count']++;
  $num = 3 - $_SESSION['count'];
  echo $num.' login attempts left.';
  if($_SESSION['count'] < 0)
    {
        session_destroy("count");
        unset($_SESSION["count"]);
        echo 'negative :/';
    }

}
if($_SESSION['count'] == 3)
{
    echo 'Your session is locked for 30 minutes.';
    if(!$_SESSION['timeout']) 
    {
        $_SESSION['timeout'] = time();
    }
    $st = $_SESSION['timeout'] + 180; //session time is 30 minutes
    if(time() < $st)
    { }
    elseif(time() >= $st) {
        session_destroy("count");
        session_destroy("timeout");
        unset($_SESSION['count']);
        unset($_SESSION['timeout']);
    }

}
?>

Somewhere the is an error but I can't find it :( I just need to limit the login attempts without using a database, just simple sessions.

Can you help me?

3 Answers3

0

First of, your second if should be an else I think.

if (!isset($_SESSION['count'])) {
  $_SESSION['count'] = 0;
} else {
...

Otherwise the first statement will check if $_SESSION['count'] is unset. If so it will set it to 0. Then for the second if it will be set and $_SESSION['count']++; will then alway increase this count to 1. So it will at least always be 1.

The second thing is that you don't decrease the count anywhere in the code. So it will never reach 0.

If you explain more on what the exact error is, we could help you better.

Please keep in mind that session base authentication can be annuled using easy methods. E.g. visiting your site through tor or use a proxy every time the login limit has been reached.

cb0
  • 8,415
  • 9
  • 52
  • 80
0

You think a hacker is gonna store a session cookie and help you out?

You can't do brute-force protection using sessions. You need application state.

Here's my answer to a previous question: Block request for multiple unsuccessful logins for a period of time

Neil McGuigan
  • 46,580
  • 12
  • 123
  • 152
-1

You don't need to write to a file. Foreach time your user tries to login and it returns false. You should add +1 to your _SESSION['count']. Put that code into a function. Your _SESSION['count'] is global so when its 3 your user will be locked out.