I have been working on a website on a localhost and have just tried to upload it to a free webserver so I can get some testers, for some reason my code is being reported as malware and is being blocked by my antivirus, this means I can't see anything when visiting it apart from the ERR_CONNECTION_RESET. Have you guys got any ideas as to why this code is being detected as malware?
LOGIN.php
<?php
include('classes/db.php');
if (db::maintenance()) {
die('This site is currently going under maintenance, please check back again shortly.');
}
if (isset($_POST['submit'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (db::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
if (password_verify($password, db::query('SELECT password FROM users WHERE username=:username', array(':username'=>$username))[0]['password'])) {
echo "Logged in!";
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
$user_id = db::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
db::query('INSERT INTO login_tokens VALUES (NULL, :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$user_id));
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie('SNID_', '1', time() + 60 + 60 * 24 * 3, '/', NULL, NULL, TRUE);
header('Location: index.php');
} else {
echo "Incorrect password";
}
} else {
echo "User not registered!";
}
}
?>
<h1>Login to your account</h1>
<form action="login.php" method="post">
<input type="text" name="username" value="" placeholder="Username"><p />
<input type="password" name="password" value="" placeholder="Password"><p />
<input type="submit" name="submit" placeholder="Login"><p />
</form>
DB.php
(I have changed the connection to false data, and changed it to the correct data when uploading it to the host.)
<?php
class db {
private static function connect () {
$conn = new PDO('mysql:host=localhost;dbname=users;,charset=utf8', 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
public static function query ($sql, $params = array()) {
$statement = self::connect()->prepare($sql);
$statement->execute($params);
if (explode(' ', $sql)[0] == 'SELECT') {
$result = $statement->fetchAll();
return $result;
}
}
public static function notify ($userid) {
$notifications = db::query('SELECT forum_members.forum_id, notifications.user_id, notifications.post_id, notifications.forum_id, notifications.post_body, notifications.creation, notifications.type FROM forum_members, notifications WHERE (notifications.forum_id=forum_members.forum_id OR notifications.forum_id=0) AND notifications.user_id=forum_members.user_id ORDER BY notifications.post_id DESC');
return $notifications;
}
public static function maintenance () {
return false;
}
}
?>
Which type of address do you use to enter the website? PHP source doesn't display to browsers, so PHP isn't the problem.
If you enter in with a hostname (Ex. .....2cc.brad....net) Then it'll automatically get detected as a "malware" for beginner safety, if ur accessing it from localhost/127.0.0.1 it should be fine, but if ur accessing it from a host that's marked as malware, than yep.
Related
This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 5 years ago.
I am trying to do something new in PHP, counting rows in a MYSQL database.
But it keeps spitting out errors as soon as I put echo $rows in it.
Can someone please help me?
Here is my login code.
<?php
'include('classes/DB.php');
if (isset($_POST['login'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (DB::query('SELECT username FROM users WHERE username=:username', array(':username'=>$username))) {
// if (DB::query('SELECT token FROM login_tokens WHERE user_id=1')<=5) {
if (password_verify($password, DB::query('SELECT password FROM users WHERE username=:username', array(':username'=> $username))[0]['password'])) {
echo 'Logged in!';
$query = DB::query('SELECT * FROM login_tokens WHERE user_id=:user_id', array(':user_id'=>$user_id));
$rows = mysql_num_rows($query);
echo $rows;
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
$user_id = DB::query('SELECT id FROM users WHERE username=:username', array(':username'=>$username))[0]['id'];
DB::query('INSERT INTO login_tokens VALUES (0, :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$user_id));
setcookie("SNID", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie("SNID_", '1', time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);
} else {
echo 'Incorrect Password!';
}
// } else {
// echo 'You already logged in on 5 different devices!'
// }
} else {
echo "User not registered! Create account <a href='http://follome.ddns.net/create-account.php'>here</a>!";
}
}
?>
<h1>Login to your account</h1>
<form action="login.php" method="post">
<input type="text" name="username" value="" placeholder="Username ..."><p />
<input type="password" name="password" value="" placeholder="Password ..."><p />
<input type="submit" name="login" value="Login">
</form>
And my DB class:
<?php
class DB {
private static function connect() {
$pdo = new PDO('mysql:host=127.0.0.1;dbname=socialnetwork;charset=utf8', 'root', 'Daan0109');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement-> execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
You can't mix the db extensions (PDO, mysqli, mysql). Furthermore, mysql was deprecated and is removed in php7.
You should use the PDO variant of mysql_num_rows()
http://php.net/manual/de/pdostatement.rowcount.php
But you need the PDOStatement object to call this. Otherwise, if you always return fetchAll(), you can just use a simple count()
It's because you use PDO, so you should check the row number with its rowcount.
http://php.net/manual/en/pdostatement.rowcount.php
Also, I would suggest you to use a framework or at least an ORM to support your goals, because otherwise you will waste a lot of time implementing features, which are aleady done. For ORM I think Doctrine is a good choice, and Laravel is an easy-to-start framework. I hope I could help you.
I have a login script and a functions.php script to check if the session username and cookie are set. When the user logs in, if they select the remember me, the cookie is supposed to set. But the problem is that, the script works, but the cookie doesn't set so the user is not being logged in. I've searched through so many topics on here and tried as many solutions as possible, but I still either get the same result or end up giving me more errors.
if (isset($_POST['rem']) && $_POST['rem'] == 'on') > {
setcookie('MCLatestUser', $token, 31622400, > '/');
session_regenerate_id(true);
}
This is the part of the code that should set the cookie if remember is checked.
Log.php (Since I use an ajax login script, the url is set to this):
<?php
include_once 'db.php';
include_once 'functions.php';
error_reporting(-1);
if(isset($_POST['email'])) {
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$password = $mysqli->real_escape_string($_POST['password']);
try {
$check = mysqli_query($mysqli, "SELECT * FROM users WHERE email='$email'");
$res = mysqli_num_rows($check);
if($res > 0) {
while($run = mysqli_fetch_array($check, MYSQLI_ASSOC)) {
$blocked = $run['blocked'];
$deactivated = $run['deactivated'];
$paused = $run['paused'];
$verified = $run['verified'];
$rank = $run['rank'];
$token = $run['token'];
$pass = $run['password'];
$pbackup = $run['pbackup'];
if($verified == 'true') {
if($blocked == 'true') {
echo 'Looks like your account was blocked. If you think this is an error, please contact an admin via support#mclatest.com';
} else if($deactivated == 'true') {
echo 'Looks like your account has been deactivated. If you think this is an error, please contact an admin via support#mclatest.com';
} else if($paused == 'true') {
echo 'Looks like your account is frozen. If you think this is an error, please contact an admin via support#mclatest.com';
} else {
if(password_verify($password, $pass)) {
$timestamp = time();
// Authenticated, set session variables
$_SESSION['username'] = $run['username'];
if (isset($_POST['rem']) && $_POST['rem'] == 'on') {
setcookie('MCLatestUser', $token, 31622400, '/');
session_regenerate_id(true);
}
$sql = mysqli_query($mysqli, "UPDATE users SET Ip = '$ipaddress', login_ip = '$ipaddress', latest_login_date = '$now', login_date = '$date', login_time = '$time', login_day = '$day', login_month = '$month', login_year = '$year', status = '$timestamp' WHERE email = '$email'");
if($sql) {
echo "Success!";
} else {
echo "Error login in";
}
// do stuffs
} else if(password_verify($password, $pbackup)) {
$timestamp = time();
// Authenticated, set session variables
$_SESSION['username'] = $run['username'];
if (isset($_POST['rem']) && $_POST['rem'] == 'on') {
setcookie('MCLatestUser', $token, 31622400, '/');
session_regenerate_id(true);
}
$sql = mysqli_query($mysqli, "UPDATE users SET Ip = '$ipaddress', login_ip = '$ipaddress', latest_login_date = '$now', login_date = '$date', login_time = '$time', login_day = '$day', login_month = '$month', login_year = '$year', status = '$timestamp' WHERE email = '$email'");
if($sql) {
echo "Success!";
} else {
echo "Error login in";
}
// do stuffs
} else {
echo "<h4 style='font-weight:bold;font-family:arial;margin:8px'>Your password is incorrect, please try again. If you still get this error after using your backup password, please <a href='https://mclatest.com/community/reset.php?r=password'>reset</a> your password</h4>";
}
}
} else {
echo "<h4 style='font-weight:bold;font-family:arial;margin:8px'>You need to verify your account. Please click this link to <a href='https://mclatest.com/community/confirm.php?email=".$email."&token=".$token."'>verify your account</a></h4>";
}
}
} else {
echo 'No records of that user have been found!';
}
} catch(PDOException $e){
echo $e->getMessage();
}
} else {
echo "Invalid email";
}
Login.php (the html and ajax form):
<form id="login_form" style="text-align:center" method="post">
<script>
$(document).ready(function() {
$("#login").click(function(e) {
e.preventDefault();
var email = $("#email").val();
if (email = "") {
$("#error_msg").html("<h4>Email cannot be empty</h4>");
} else {
var data = $("#login_form").serialize();
$.ajax({
type: "POST",
url: "../inc/log.php",
data: data,
beforeSend: function() {
$("#error_msg").fadeOut();
$("#login").val('sending ...');
},
success: function(data) {
if (data == "Success!") {
// alert("Works"); //for testing purposes
window.location.href = "index.php";
} else {
$("#error_msg").fadeIn(1000, function() {
$("#error_msg").html('<div style="border:1px solid: red; background:rgba(255,0,0,0.9;)">'+data+'!</div>');
$("#login").val('Login');
});
}
},
error: function(data) {
alert("Process Failed!");
}
});
return false;
}
});
});
</script>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label ">
<label for="input_email" class="mdl-textfield__label">Email</label>
<input type="email" name="email" class="mdl-textfield__input" maxlength="255" id="input_email" />
</div>
<br>
<div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<label for="input_password" class="mdl-textfield__label">Password</label>
<input type="password" name="password" class="mdl-textfield__input" maxlength="255" id="input_password" />
</div>
<br>
<label style="width:auto !important" for="remember_me" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" >
<input name="rem" type="checkbox" id="remember_me" class="mdl-checkbox__input" checked />
<span class="mdl-checkbox__label">Stay logged in?</span>
</label>
<br>
<nav style="width:auto !important;display:-webkit-box;-webkit-box-pack:center" class="mdl-navigation">
<a class="mdl-navigation__link" href="forgot.php?ftype=password">Forgot Password?</a> |
<a class="mdl-navigation__link" href="register.php">Register?</a>
</nav>
<br>
<input type="submit" id="login" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" name="login" value="Login"/>
</form>
functions.php (this is the portion of the script to check the session and cookie variables):
function loggedIn() {
if (isset($_SESSION['username']) && !empty($_SESSION['username']) && isset($_COOKIE['MCLatestUser'])) {
return true;
} else {
return false;
}
}
Script works but cookies aren't being sent. I'm at my wits end here, been working on this for over 4-5 hours now, had over 35 chrome tabs open just to figure this out. I am probably overlooking a minor detail. Login Page Link
It works if i remove the && $_COOKIE['MCLatestUser'] from the function script
setcookie('MCLatestUser', $token, 31622400, '/');
This method has some problems in the third parameter.It should be based on the current time.
PHP: setcookie - Manual
I figured it out. It turns out it was the browser's fault. I tried it on Microsoft Edge and Mozilla Firefox and it worked. So I looked about for that issue and all I had to do was clear my cookies and site data on chrome. Thank you to those who helped and those who wanted to but couldn't/didn't.
I have a simple account creation script that is not working. I know that there are no connection errors because the login works fine. Also, I turned on error-reporting (made it -1) but it shows no errors
This is my code in snippets, thanks
HTML
<form method="post">
<input type="text" name="newUsername" placeholder="Username"/>
<input type="password" name="newPassword" placeholder="Password"/>
<input type="submit" name="signUp" value="Sign Up!"/>
</form>
Then PHP:
if($_POST['signUp']) {
$username = $_POST['newUsername'];
$pass = $_POST['newPassword'];
$signedUp = SignUp($Username,$pass);
echo $signUpCode[$signedUp]; // See the SignUp function in prefunc.php
} elseif($_POST['LogIn']) {
$username = $_POST['Username'];
$password = $_POST['Password'];
$loggedIn = LogIn($username,$password);
echo $logInCode[$loggedIn];
}
$signUpCode = Array(
"-3"=>"Logged in already - can't sign up!",
"-2"=>"Username already exists!",
"-1"=>"Failed to sign up - please try again!",
"1"=>"Signed up, and logged in successfully!"
);
function SignUp($Username,$Password) {
$Username = preg_replace("/[^a-zA-Z0-9]/","",$Username);
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(getCurrentId()){
return -3;
}
if(!mysql_num_rows($u)) {
mysql_query("INSERT INTO Users SET Username='$Username',Password=''$Password") or die(mysql_error());
$u = mysql_query("SELECT * FROM Users WHERE LOWER(Username)=LOWER('$Username')");
if(mysql_num_rows($u)) {
LogIn($Username,$Password);
return 1;
} else {
return -1;
}
}
return -2;
}
Are you sure you re executing the insert query?
also the query sintax is wrong, try this: insert into user ( username,password) values ('admin','1234').
finally you must fix security issue, your code is affected by sql injection
I have been struggling with this one for hours and hours and just cannot figure out what I'm missing.
I'm trying to build a cookie-less login form that also has no information in session variables that would harm the app if an attacker would be able to modify them.
All of my pages have the below code included.
I have 2 issues:
Every time I click on another page it acts like $_SESSION['token'] was empty and goes to the login page like if it was the first visit.
It returns $tokenid and $tokentype empty however I'm calling them both every time a page is loading (aiming to avoid having to put them into a session variable).
This is my current code:
<?php
define('TIMEOUTMIN', 15);
define('LOCKOUTMIN', 10);
define('LOCKOUTNUM', 3);
include("includes/pp/pbkdf2.php"); // this is basically calling the validate_password function
include ("includes/vars/vars_dbconn.php"); // this contains the db data and $pdo
$userid = $_POST['userid'];
$userpw = $_POST['password'];
$deltoq = "UPDATE LoginUser SET token = ?, online = ? WHERE online < ?";
$prepdeltoq = $pdo->prepare($deltoq);
$prepdeltoq->execute(array(NULL,NULL,time()));
$loginq = "SELECT * FROM LoginUser WHERE ID = ?";
$preplq = $pdo->prepare($loginq);
$preplq->execute(array($userid));
$getuser = $preplq->fetch(PDO::FETCH_ASSOC);
$dbid = $getuser['ID'];
$dbpass = $getuser['hash'];
$dbbp = $getuser['bp'];
$dbltime = $getuser['ltimeout'];
$logintoq = "SELECT * FROM LoginUser WHERE token = ?";
$prepltq = $pdo->prepare($logintoq);
$prepltq->execute(array($_SESSION['token']));
$getoken = $prepltq->fetch(PDO::FETCH_ASSOC);
$tokenid = $getoken['ID'];
$tokentype = $getoken['type'];
$totoken = $getoken['token'];
$prolonglock = $pdo->prepare("UPDATE LoginUser SET ltimeout = ? WHERE ID = ?");
$addbp = $pdo->prepare("UPDATE LoginUser SET bp = ? WHERE ID = ?");
$loginwhen = $pdo->prepare("UPDATE LoginUser SET lastlogin = ? WHERE ID = ?");
$loginlogq = $pdo->prepare("INSERT INTO LoginUserLog (ID, action)
VALUES(:ID, :action)");
$logintokenid = $pdo->prepare("UPDATE LoginUser SET token = ? WHERE ID = ?");
$loginonid = $pdo->prepare("UPDATE LoginUser SET online = ? WHERE ID = ?");
$loginontok = $pdo->prepare("UPDATE LoginUser SET online = ? WHERE token = ?");
if(!function_exists('LoginUser')) {
function LoginUser($pwmessage) {
if (session_name() <> 'MyWebApp') session_name('WesoftskyLogin');
if (!session_id()) session_start();
$_SESSION['token'] = '';
include ("includes/header.php"); ?>
<meta name="description" content="Login - MyWebApp"/>
<title>Login - MyWebApp</title>
<script type="text/javascript">
event.keyCode == '';
function enterTab() {
if (event.keyCode == 13) {
var passInput = document.getElementById("password");
passInput.focus();
}
}
</script>
</head>
<body onkeyup="enterTab()">
<div id="homewrap">
<div id="hometitle">MyWebApp</div>
</div>
<div id="id_formwrap">
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI'].$_SERVER['QUERY_STRING']); ?>" method="post">
<?php if (empty($pwmessage)) echo '<div>Please enter your login details</div>'; else echo '<div style="color:red">'.$pwmessage.'</div>'; ?><br />
Login ID<br />
<input type="text" name="userid" id="id" onKeyPress="return noenter(event)" /><br /><br />
<script>document.getElementById("id").focus()</script>
Password<br />
<input type="password" name="password" id="password" /><br /><br />
<input type="submit" name="login" id="Submit" value="Login" />
</form>
</div>
</body>
</html>
<?php exit();
}
}
if(!function_exists('ProlongTime')) {
function ProlongTime() {
global $userid;
global $logintokenid;
global $loginonid;
global $loginontok;
$timeoutodb = (time () + TIMEOUTMIN*60);
if (!empty($userid)) {
$_SESSION['token'] = bin2hex(mcrypt_create_iv(16, MCRYPT_DEV_URANDOM));
$logintokenid->execute(array($_SESSION['token'], $userid));
$loginonid->execute(array($timeoutodb, $userid));
} else {
$loginontok->execute(array($timeoutodb, $_SESSION['token']));
}
}
}
if ($dbltime > time()) {
$lockcheck = time() + LOCKOUTMIN*60;
$prolonglock->execute(array($lockcheck,$userid));
LoginUser('Your account is currently locked');
}
if(isset($_POST['logout'])) {
$action = "Logged OUT";
$loginlogq->execute(array(':ID' => $tokenid, ':action' => $action));
LoginUser('Logged out');
}
if (isset($_POST['login'])) {
if ($dbid AND validate_password($userpw, $dbpass)) { // Good login info
//session_regenerate_id(true);
$action = "Logged IN";
$loginlogq->execute(array(':ID' => $userid, ':action' => $action));
$loginwhen->execute(array(time(), $userid));
$addbp->execute(array(NULL, $userid));
ProlongTime();
} else { // Bad login info
if ($dbbp >= LOCKOUTNUM-1) {
$lockbp = time() + LOCKOUTMIN*60;
$prolonglock->execute(array($lockbp,$userid));
$action = "Locked (wrong password)";
$loginlogq->execute(array(':ID' => $userid, ':action' => $action));
LoginUser('Your account has been locked');
}
$addbp->execute(array($dbbp+1, $userid));
$action = "Failed login";
$loginlogq->execute(array(':ID' => $userid, ':action' => $action));
LoginUser('Username or password is incorrect');
}
} elseif (empty($_SESSION['token'])) { // Loading the page first time (new session)
LoginUser('');
} elseif ($_SESSION['token'] <> $totoken) { // Session timeout
$action = "Logged OUT (expired)";
$loginlogq->execute(array(':ID' => $tokenid, ':action' => $action));
echo 'tokenid: '.$tokenid;
} else ProlongTime(); // While using the app and still within time
$pdo = null;
?>
You need to put
session_start()
in the starting of the page.
I know I'm missing something here. I've been staring at this short script for a while now and I can't see where it's going wrong.
Here's my script:
http://pastebin.com/FtNeNtwj
And here's the script in action:
http://troop007.tk/login.007?action=login
The username and password are both "demo". I type in the username and password, press log in, and instead of taking me to login.007?action=logincheck, it never leaves login.007?action=login.
I have one MySQL table called users, and inside that table there are two fields: username and password.
The script I'm using is a modified version of the script found here: http://www.phpeasystep.com/phptu/6.html
I would scrap that tutorial, login security is not tobe looked upon lightly, you should not have plaintext passwords in the database they should be hashed with a salt and both should change upon successful login.
Here is A secure login script:
It uses PDO for the database connection, the actual login form uses random keys for login eg. not username/password. Passwords are hashed with sha512 x 25k times and with a 16byte key salt, brute force protection. Hope it helps.
<?php
session_start();
/**
* Table
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) DEFAULT NULL,
`pass_hash` varchar(255) DEFAULT NULL,
`pass_salt` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=0 ;
*/
//DB Stuff
define('DBHOST','localhost');
define('DBNAME','yourdb');
define('DBUSER','root');
define('DBPASS','');
//End Config:---
//Open a PDO Database connection
try {
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch (Exception $e){
die('Cannot connect to mySQL server.');
}
class Login{
public $db;
public $user;
public $pass;
public $error;
// sha512
public $algo = '$6';
// Cost parameter, 25k iterations
public $cost = '$rounds=25000$';
function __construct(PDO $db){
$this->db = $db;
$this->global_salt = sha1($_SERVER['HTTP_HOST']);
}
/**
* Return a random seed for the mt_rand function
*/
function make_seed(){
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
/**
* Return a random unique salt for new created hash/crypt function salts
*/
function unique_salt(){
$salt = null;
mt_srand($this->make_seed());
for($i=0;$i < mt_rand(1,10);$i++){
$salt = sha1($this->global_salt.$salt.mt_rand().uniqid().microtime(true));
}
return substr($salt,0,16);
}
/**
* Hash a given password and store parts in:
* $this->salt = a unique 16 byte salt
* $this->hash = The full crypted hash sting including algo/cost/salt/crytedpassword
* $this->full_salt = Just algo/cost/salt section, the first 33 bytes
* $this->hashed_password = Just crytedpassword section, proceeding bytes after first 33 bytes
*
*/
function hash($password){
$this->salt = $this->unique_salt();
$this->full_hash = crypt($password, $this->algo.$this->cost.$this->salt);
$this->full_salt = substr($this->full_hash, 0, 33);
$this->hashed_password = substr($this->full_hash, 33);
return $this->full_hash;
}
/**
* Method to validate the given crypto hash against the given password
*/
function check_password($hash, $salt, $password){
$hash = ($this->algo.$this->cost.$salt.'$'.$hash);
if($hash == crypt($password, substr($hash, 0, 33))){
//Regenerate new hash and salt for given password
$this->update_keys();
$this->status = true;
$_SESSION['logged_in']=true;
return true;
}else{
$this->status = false;
return false;
}
}
/**
* Set error
*/
function set_error($type,$value){
$this->error[$type]=$value;
}
/**
* Output error
*/
function error($type){
echo (isset($this->error[$type]))?$this->error[$type]:null;
}
/**
* Logout and regenirate session and redirect to index
*/
static function logout(){
unset($_SESSION['logged_in']);
session_regenerate_id(true);
exit(header('Location: ./index.php'));
}
function anti_brute($intval){
if(!isset($_SESSION['access_time'])){
$_SESSION['access_time']=time();
}else{
$t = time()-$_SESSION['access_time'];
if($t <= $intval){
$this->set_error('global','Time violation');
$_SESSION['access_time']=time();
return true;
}
$_SESSION['access_time']=time();
return false;
}
}
function process_login(){
if($_SERVER['REQUEST_METHOD']=='POST'){
$this->user = (isset($_SESSION['userParam']) && isset($_POST[$_SESSION['userParam']]))?$_POST[$_SESSION['userParam']]:null;
$this->pass = (isset($_SESSION['passParam']) && isset($_POST[$_SESSION['passParam']]))?$_POST[$_SESSION['passParam']]:null;
$this->create = (isset($_SESSION['createParam']) && isset($_POST[$_SESSION['createParam']]))?$_POST[$_SESSION['createParam']]:null;
$cont = true;
if($this->user == null || strlen($this->user) <= 2){$this->set_error('user','Please enter a username!'); $cont=false;}
if($this->pass == null || strlen($this->pass) <= 2){$this->set_error('pass','Please enter a password!'); $cont=false;}
if($cont==true){
//Alls good continue
if($this->create != null && $this->create=='1'){
//Check user for new account
if($this->check_user()==true){$this->set_error('user','Username already taken.');return;}
//Create account
$this->create_account();
}else{
//Stop really fast request 2 seconds
if($this->anti_brute(2)==false){
//Attempt to login
$this->check_login();
}
}
}else{
//Error with form
$this->set_error('global','Please fill in login form!');
}
}
}
function check_user(){
$sql = 'SELECT 1 FROM users WHERE username=:username';
$statement = $this->db->prepare($sql);
$statement->bindParam(':username', $this->user, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
if(!empty($result)){return true;}else{return false;}
}
function check_login(){
$sql = 'SELECT pass_hash, pass_salt FROM users WHERE username=:username';
$statement = $this->db->prepare($sql);
$statement->bindParam(':username', $this->user, PDO::PARAM_STR);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_ASSOC);
$this->check_password($result['pass_hash'], $result['pass_salt'], $this->pass);
}
function create_account(){
//Create new account
$this->hash($this->pass);
$sql = 'INSERT into users (username, pass_hash, pass_salt) VALUES (:username, :pass_hash, :pass_salt)';
$statement = $this->db->prepare($sql);
$statement->bindParam(':username', $this->user, PDO::PARAM_STR);
$statement->bindParam(':pass_hash', $this->hashed_password, PDO::PARAM_STR);
$statement->bindParam(':pass_salt', $this->salt, PDO::PARAM_STR);
$statement->execute();
$this->status = true;
$_SESSION['logged_in']=true;
}
function update_keys(){
//Update account password hash & salt
$this->hash($this->pass);
$sql = 'UPDATE users SET pass_hash=:pass_hash, pass_salt=:pass_salt WHERE username=:username';
$statement = $this->db->prepare($sql);
$statement->bindParam(':username', $this->user, PDO::PARAM_STR);
$statement->bindParam(':pass_hash', $this->hashed_password, PDO::PARAM_STR);
$statement->bindParam(':pass_salt', $this->salt, PDO::PARAM_STR);
$statement->execute();
$this->status = true;
$_SESSION['logged_in']=true;
}
}//END Login class
//Logout handler
if(isset($_GET['logout'])){ Login::logout(); }
$login = new Login($db);
//Login handler
$login->process_login();
//Debug
echo '<pre>';
print_r($login);
echo '</pre>';
//Check login status
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']==true){
//Logged in
echo 'Logout';
}else{
//Not Logged In
//Show login form & create uniqie parrams for user/pass/create post keys
$_SESSION['userParam'] = sha1(uniqid().microtime(true));
$_SESSION['passParam'] = sha1(uniqid().microtime(true));
$_SESSION['createParam'] = sha1(uniqid().microtime(true));
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Secure Login</title>
</head>
<body>
<h1>Secure Login Example</h1>
<h3>Please login:</h3>
<?php $login->error('global'); ?>
<form method="POST" action="">
<label for="user">Username : </label>
<input type="text" name="<?=$_SESSION['userParam'];?>" size="29"> <?php $login->error('user'); ?>
<br />
<label for="pass">Password : </label>
<input type="text" name="<?=$_SESSION['passParam'];?>" size="29"> <?php $login->error('pass'); ?>
<br />
<input type="submit" value="Login"> and create my account:<input type="checkbox" name="<?=$_SESSION['createParam'];?>" value="1">
</form>
</body>
</html>
<?php } ?>