Login Script (another~)
Posted: Sun Mar 08, 2009 8:54 pm
Code: Select all
<?php
/*
matt lo
simple login check
*/
class login {
protected $_error = NULL; // error set
protected $_goto = NULL; // goto page ex: index.php or ?id=2
// construct, what is the class going to do
public function __construct($goto) { // if login accepted, go to what page (same for logout)
// REQUIRED HIDDEN FIELD!!! handlecheck, its to identify the login form
if(!isset($_POST['handlecheck'])) {
throw new Exception("handlecheck not detected in the post form");
}
// create a unique token to login, i will make this random per visit in the future
if($_POST['handlecheck'] != md5('Lg51')) {
throw new Exception("handlecheck token does not match");
}
$this->_goto = $goto;
}
// check login fields
public function check_login() {
// sleep, bot filter
sleep(5); // 5 seconds
// additional room for custom fields....
if($_POST['email'] == '' || $_POST['password'] == '') {
$this->_error = "Email and/or password are invalid.";
}
// this checks if email/password right
$q = mysql_query("SELECT * FROM `site_users` WHERE `email` = '".$_POST['email']."' AND `password` = '".md5($_POST['password'])."' LIMIT 0,1");
// if theres a match, everything is good
if(mysql_num_rows($q) == 0) {
$this->_error = "Email and/or password are invalid.";
}
if($this->boolcheck() !== false) {
// row data from id
$row = mysql_fetch_assoc($q);
//if remember me is set in form (checkbox)
if(isset($_POST['rem'])) {
if($_POST['rem'] == '1') {
// set a token for unique id
$token = md5(uniqid(rand(), true));
// set a remember me cookie, expires every 2 weeks
setcookie('529_rem_me_100', $token, time()*3600*24*14);
// save token in database
mysql_query("UPDATE `site_users` SET `rem_token` = '".$token."' WHERE `id` = '".$row['id']."'");
if(mysql_error()) {
throw new Exception(mysql_error());
}
}
}
$_SESSION['id'] = $row['id'];
header("location: ".$this->_goto);
} else {// log attempt
// insert attempt data into sql
mysql_query("INSERT INTO `ip_login_log` (`ip`, `emailattempt`, `datestamp`) VALUES ('".$_SERVER['REMOTE_ADDR']."', '".$_POST['email']."', '".date("Ymd")."')");
if(mysql_error()) {// if sql error
throw new Exception(mysql_error());
}
}
}
public function boolcheck() { // boolean return if any errors happened
if($this->_error == NULL) {
return true;
} else {
return false;
}
}
// if errors, return the response
public function error_response() {
return $this->_error;
}
public function logout() {
// delete cookie
setcookie('529_rem_me_100', '-', time()-3600);
unset($_SESSION['id']);
header("location: ".$this->_goto);
}
}
?>before coding, do if(isset($_POST['sdafsd'])) {
$l = new login('p.php');
$l->check_login();
if($l->boolcheck() === false) {
echo $l->error_response();
}
}