Notice: Undefined index: username in E:\xampp\htdocs\test\test2.php on line 26
Notice: Undefined index: password in E:\xampp\htdocs\test\test2.php on line 28
Notice: Undefined index: token in E:\xampp\htdocs\test\test2.php on line 31
Code: Select all
<?php
session_start();
error_reporting(E_ALL);
class Login
{
private $_id;
private $_username;
private $_password;
private $_passmd5;
private $_login;
private $_access;
private $_errors;
private $_token;
public function __construct()
{
$this->_login = isset($_POST['login'])? 1 : 0;
$this->_id = 0;
$this->_username = ($this->_login)? $this->filter($_POST['username']) : $_SESSION['username'];
$this->_password = ($this->_login)? $this->filter($_POST['password']) : '';
$this->_passmd5 = ($this->_login)? md5($this->_password) : $_SESSION['password'];
$this->_access = 0;
$this->_errors = array();
$this->_token = $_POST['token'];
}
public function isloggedin()
{
($this->_login)? $this->verifypost() : $this->verifydatabase();
}
public function verifypost()
{
try{
if(!$this->verifydata())
throw new Exception("Invalid data submission!");
if(!$this->verifydatabse())
throw new Exception("Invalid username/password!");
if(!$this->istokenvalid())
throw new Exception("Invalid form submission!");
$this->_access = 1;
$this->_registervalues();
}
catch(Exception $e)
{
$this->_errors[] = $e->getMessage();
}
}
public function istokenvalid()
{
return(!isset($_SESSION['token']) || $this->_token != $_SESSION['token'])? 1 : 0;
}
public function verifydata()
{
return (preg_match('/[^a-zA-Z0-9]{5,12}$/',$this->_username) && preg_match('/[^a-zA-Z0-9]{5,12}$/',$this->_password))? 1 : 0;
}
public function filter($var)
{
return preg_replace('/[^a-zA-Z0-9]/','',$var);
}
public function verifydatabase()
{
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());
$data = mysql_query("SELECT * FROM users WHERE username = '{$this->_username}' AND password = '{$this->_passmd5}' ");
if(mysql_num_rows($data))
{
list($this->_id) = @array_values(mysql_fetch_assoc($data));
return true;
}
else
return false;
}
public function registervalues()
{
$_SESSION['username'] = $this->_username;
$_SESSION['ID'] = $this->_id;
$_SESSION['password'] = $this->_passmd5;
}
public function showerrors()
{
echo "<h3>Errors</h3>";
foreach($this->_errors as $key=>$value)
{
echo $value."<br>";
}
}
}
$login = new Login();
if($login->isloggedin())
{
echo $_SESSION['username'];
}
else{
$login->showerrors();
}
$token = $_SESSION['token'] = md5(uniqid(mt_rand(),true));
?>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='POST'>
<table>
<tr><td>
Username:
</td><td>
<input type='text' name='username'>
</td></tr>
<tr><td>
Password:
</td><td>
<input type='password' name='password'>
<input type='hidden' name='token' value='<?php echo $token; ?>'>
</td></tr>
</table>
<input type='submit' name='login' value='Log In'>
</form>