Essential PHP Security Book Cover
Essential PHP Security by Chris Shiflett
About | Contents | Buy Now | Reviews | Errata | Code
  1. Foreword
  2. Preface
  1. Introduction
  2. Forms and URLs
          ch02.pdf
  3. Databases and SQL
  4. Sessions and Cookies
          ch04.pdf
  5. Includes
  6. Files and Commands
  7. Authentication and Authorization
  8. Shared Hosting
  1. Configuration Directives
  2. Functions
  3. Cryptography
  4. Index

Throttle an Authentication Form

(Chapter 7, Authentication and Authorization - Pg 66-67)

< Back to Code Repository

<?php

/* mysql_connect() */
/* mysql_select_db() */

$clean = array();
$mysql = array();

$now time();
$max $now 15;

$salt 'SHIFLETT';

if (
ctype_alnum($_POST['username']))
{
    
$clean['username'] = $_POST['username'];
}
else
{
    
/* ... */
}

$clean['password'] = md5($salt md5($_POST['password'] . $salt));
$mysql['username'] = mysql_real_escape_string($clean['username']);

$sql "SELECT last_failure, password
        FROM   users
        WHERE  username = '
{$mysql['username']}'";

if (
$result mysql_query($sql))
{
    if (
mysql_num_rows($result))
    {
        
$record mysql_fetch_assoc($result);

        if (
$record['last_failure'] > $max)
        {
            
/* Less than 15 seconds since last failure */
        
}
        elseif (
$record['password'] == $clean['password'])
        {
            
/* Successful Login */
        
}
        else
        {
            
/* Failed Login */

            
$sql "UPDATE users
                    SET    last_failure = '
$now'
                    WHERE  username = '
{$mysql['username']}'";

            
mysql_query($sql);
        }
    }
    else
    {
        
/* Invalid Username */
    
}
}
else
{
    
/* Error */
}