I re-wrote your code how I personally would write it. Just want to present a different perspective... OK, so really, I can't sleep and I like your enthusiasm
I added a little functionality to track user login attempts and left a little bit of homework in there, if you are up to the challenge. Otherwise you may just delete what I've done and go on your merry way.
A few tips:
magic quotes can throw a wrench in your plan, in a hurry. If magic quotes are enabled on the server and then you escape the data before putting it through the database, you run the risk of double-escaping, or negating escaping, which can cause you headaches in the best case scenario.
escaping data before it gets put into a query/database is the LAST thing to do before it goes into the query or database. The last
thing you want to do is escape the data, then change it, then run it through the database. This leaves the door wide open for un-intentional errors or sql injection.
As far as starting a session. Feel free to start it at the beginning of each page, whether it is accessed or not on that particular page. It uses an insignificant ammount of resources (provided you aren't abusing it, and storing a rediculous ammount of data within it).
Also, rather then echoing a hyperlink for the user to follow to the next page, you can use the header() function and automatically direct them where you want them to go. It's the preferred method to keep any users from monkey'ing with your system.
try to use include_once(), instead of include(). They do the same basic function, except if you try to include the same file by accident later, it wont be included.
I dont fully understand how your connect() function works. Typically you would assign a database connection to a variable, as in: $database = connection(). However, your method might just work fine, provided it's implemented correctly. I just cant see that part of the code. Be sure to test it on your own to verify it's doing what you intend.
lastly, pay special attention to how I constructed your SQL query, using back-ticks (`) around column and table names and singe quotes(') around data. Dont forget to terminate the query with a semi colon either. It's proper syntax, good code, and prevents SQL injection.
ok, a shot of whiskey and then it's bed time for me.
Code: Select all
<?php
/**
* Ramen
* Login script
* Version 1.0
* Thanks to http://forums.devnetwork.net for their help :P
*/
# Begin Session
session_start();
# Disable Magic Quotes
if(get_magic_quotes_gpc()) {
$input = array(&$_GET, &$_POST, &$_COOKIE, &$_ENV, &$_SERVER);
while(list($k, $v) = each($input)) {
foreach($v as $key => $val) {
if(!is_array($val)) {
$input[$k][$key] = stripslashes($val);
continue;
}
$input[] =& $input[$k][$key];
}
}
unset($input);
}
# Vars
$max_login_attempts = 5;
$username = (isset($_POST['username'])) ? $_POST['username'] : "";
$password = (isset($_POST['password'])) ? $_POST['password'] : "";
# Includes
include_once(dirname(__FILE__) . '../files/functions.php'); // Always use a full path when possible
# Check to see if the form has been submitted.
if(isset($_SERVER['REQUEST_METHOD']) && strtolower($_SERVER['REQUEST_METHOD']) == "post") {
# Increment LoginAttempts Session Var
$_SESSION['loginAttempts'] = (isset($_SESSION['loginAttempts'])) ? $_SESSION['loginAttempts'] + 1 : 1;
# Check if max login attempts has been exceeded
if($_SESSION['loginAttempts'] > $max_login_attempts) {
echo "Too many login attempts. Please try again in xx minutes";
exit();
// To Do: Build code that checks if it has been xx minutes since last login
// We can do this by assigning a timestamp to the users session (i.e. $_SESSION['timestamp'] = strtotime("now"))
}
# Sanity Check
if(empty($username) || empty($password)) {
echo "Something was left blank. Please go back and try again.";
exit();
} else {
# Connect to the Database
if(!connect()) die(mysql_error());
# Query Database for user credentials
$result = mysql_query(sprintf("SELECT * FROM `{$prefix}users` WHERE username='%s' && password='%s';",
mysql_real_escape_string($username),
mysql_real_escape_string(sha1($password))));
if(mysql_num_rows($result) == 1) {
# Login Successful
mysql_close(connect()); // Close our connection.
$_SESSION['loggedin'] = 1; // The session var named loggedin is set to 1.
unset($_SESSION['loginAttempts']); // Set the loginAttempts Session Var back to 0.
header("location:https://www.mydomain.com/my_secure_index.php"); // Redirect user to user's home
exit();
} else {
# We could not find a match for what the user submitted (or a duplicate)...
echo 'Your username or password are incorrect. Please go back and try again.';
exit();
}
}
}
?>
<form action="login.php" method="post" name="submit">
Username: <br />
<input type="text" name="username" value="<?php print $username; ?>" /> <br />
Password: <br />
<input type="password" name="password" /> <br />
<input type="submit" />
</form>