Simple PHP Authentication Script

Asphyxia

Owner
Administrator
Apr 25, 2015
1,844
2
2,197
327
This is a very basic authentication script and I do not recommend using this in a production environment. Does anyone else have their own PHP login/authentication scripts? Feel free to share yours! Also, highlight security issues you notice or what could be improved. ;)

PHP:
<?php
session_start();
$setPassword = "Cake";
//You may change the password, this is just a simple system for the foundation(s) of a VERY SMALL AUTH system.
if (isset($_GET['logout'])) {
   session_destroy();
   header('Location: password.php');
}

if (isset($_SESSION['welcome'])) {
   if ($_SESSION['welcome'] == $setPassword) {
       echo "You are authorized with current credentials.";
       echo "<hr><a href='?logout'>Logout</a>";
       die;
   } else {
       echo "Your credentials have become invalid. Your session was just destroyed.";
       session_destroy();
   }
}
?>
<div align="right">
Verify your identity:
<form action="password.php" method="post">
<input type="password" name="auth">
<input type="submit" value="Authorize">
</form>
<?php
if (isset($_POST["auth"])) {
   if ($_SESSION['fails'] > 2) {
       die("Invalid login attempt.");
   }
   $auth = $_POST["auth"];
   if ($auth == $setPassword) {
       unset($_SESSION['fails']);
       $_SESSION['welcome'] = $setPassword;
       echo '
<h1>If you were not redirected, reload the page.</h1>
<meta http-equiv="refresh" content="0">
';
   } else {
       $_SESSION['fails']++;
       //echo $_SESSION['fails'];
       //echo "Invalid attempt, you have ".$_SESSION['fails']."/3 failed attempts.";
       echo "Invalid login attempt.";
   }
}
?>
</div>
 

Derp

Retired Staff
Contributor
Apr 30, 2015
933
1,017
217
Something's wrong in that script, let's see if someone can guess what that is :p
 

aequabit

Active Member
Oct 10, 2016
2
4
78
Optimized your code a bit, added IP based bans and commented everything. Should be good to learn from it.

You should also decide, if you use single or double quotes. Both look just messy.
For normal strings ('yea, i\'m so kewl'), I personally use single quotes and for strings containing variables ("Your username: $username") I use double quotes, so you can easily spot the difference.

PHP:
<?php
    /* Give your Session a name to break Session cookie stealers - and be cool :^) */
    session_name('MySecretSession');
 
    /* Start the Session */
    session_start();
 
    /* Define maximum attempts of failed logins */
    $maxFails = 3;
 
    /* Absolute path to the IP log file */
    $ipLog = __DIR__ . '/ips.txt';
 
    /* Declare an numeric array with passwords in it */
    $passwords = [
    'Cake',
    'Cookie'
    ];
 
    /* Create IP log file if it doesn't exist */
    if (!file_exists($ipLog)) {
        touch($ipLog);
    }
 
    /* Get the user's IP address - Source: http://stackoverflow.com/a/55790/5794450*/
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $userIp = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $userIp = $_SERVER['HTTP_X_FORWARDED_FOR'];
        } else {
        $userIp = $_SERVER['REMOTE_ADDR'];
    }
 
    /* If fail variable does not exist, create it */
    if (!isset($_SESSION['fails'])) {
        $_SESSION['fails'] = 0;
    }
 
    /* If the user failed three times */
    if ($_SESSION['fails'] == 3 && !strstr(file_get_contents($ipLog), $userIp)) {
        /* Add the user's IP to a list of banned IPs if it doesn't already contain it */
        $myfile = file_put_contents('ips.txt', $userIp.PHP_EOL , FILE_APPEND | LOCK_EX);
    }
 
    /* If user exceeded the count of maximal login attempts */
    if (isset($_SESSION['fails']) && $_SESSION['fails'] >= 3 || strpos(file_get_contents($ipLog), $userIp) !== false) {
        /* Kill the script and display error message to user */
        die('<font color="red">Your login tries exceeded the maximum count of of failed logins allowed.</font>');
    }
 
    /* If logout is requested */
    if (isset($_GET['logout'])) {
        /* Destroy the Session */
        session_destroy();
    
        /* Redirect the user */
        header('Location: /protected.php');
    
        /* Kill the script to prevent code being executed after the redirect */
        die();
    }
 
    /* If action is set */
    if (isset($_POST["action"]) && !empty($_POST['action'])) {
        /* If authentication was requested */
        if ($_POST['action'] == 'auth') {
        
            /* Set password variable for easier use */
            $password = $_POST['password'];
        
            /* If password list doesn't include the user's one */
            if (!(in_array($password, $passwords))) {
                /* Increase fail variable */
                $_SESSION['fails']++;
            
                /* Set authentication error message */
                $triesLeft = ($maxFails - $_SESSION['fails']);
                $_SESSION['authError'] = "The password you have entered is invalid. You have $triesLeft tries left.";
            
                /* Redirect the user */
                header('Location: /protected.php');
            
                /* Kill the script to prevent code being executed after the redirect */
                die();
            }
        
            /* If login was successful */
            unset($_SESSION['fails']);
        
            /* Set Session auth variable */
            $_SESSION['auth'] = $password;
        
            /* Redirect the user */
            header('Location: /protected.php');
        
            /* Kill the script to prevent code being executed after the redirect */
            die();
        
        }
    }
 
    /* If user is authenticated */
    if (isset($_SESSION['auth'])) {
        /* If password expired while the user was logged in */
        if (!in_array($_SESSION['auth'], $passwords)) {
            /* Set authentication error message */
            $_SESSION['authError'] = 'Your password expired.';
        
            /* Unset the auth parameter */
            unset($_SESSION['auth']);
        
            /* Redirect the user */
            header('Location: /protected.php');
        
            /* Kill the script to prevent code being executed after the redirect */
            die();
        }
    }
 
    /* If user is not authenticated */
    if (!isset($_SESSION['auth'])):
?>
<div>
    <?php /* If authError is set, display and unset it */
    if (isset($_SESSION['authError'])): ?>
    <font color="red"><?=$_SESSION['authError']?></font><br>
    <?php endif; unset($_SESSION['authError']); ?>
    Verify your identity:
    <form action="/protected.php" method="post">
        <input type="hidden" name="action" value="auth">
        <input type="password" name="password">
        <input type="submit" value="Authenticate">
    </form>
</div>
<?php else: ?>
<div>
    You are authenticated with this password: <?=$_SESSION['auth']?><br>
    <a href="/protected.php?logout">Logout</a>
</div>    
<?php endif; ?>
 
Last edited:
Top