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.
Related
I am trying to add the login function to my website, but when I clicked on the login button, the page crashes and gives the following error message:
/index.php - Uncaught Error: Call to a member function prepare() on
null in
/Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php:56
Stack trace:
0 /Users/xx/Documents/INFO2300/xxproject-3/includes/init.php(82): exec_sql_query(NULL, 'SELECT * FROM u...', Array)
1 /Users/xx/Documents/INFO2300/xx-project-3/includes/init.php(199): log_in('xx333', 'xx')
2 /Users/xxDocuments/INFO2300/xx333-project-3/index.php(2): include('/Users/xx/D...')
3 {main} thrown in /Users/xx/Documents/INFO2300/xx333-project-3/includes/init.php on line
56
Here is my code for index.php:
<?php
include("includes/init.php");
$db = open_or_init_sqlite_db('secure/gallery.sqlite', 'secure/init.sql');
$messages = array();
// Set maximum file size for uploaded files.
// MAX_FILE_SIZE must be set to bytes
// 1 MB = 1000000 bytes
const MAX_FILE_SIZE = 1000000;
// Users must be logged in to upload files!
if ( isset($_POST["submit_upload"]) && is_user_logged_in() ) {
// TODO: filter input for the "box_file" and "description" parameters.
// Hint: filtering input for files means checking if the upload was successful
$upload_info=$_FILES["box_file"];
$upload_desc=filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
if ($upload_info['error']==UPLOAD_ERR_OK){
$upload_name=basename($upload_info["name"]);
$upload_ext = strtolower( pathinfo($upload_name, PATHINFO_EXTENSION) );
$sql="INSERT INTO documents(user_id,file_name,file_ext,description)VALUES(:user_id,:file_name,:file_ext,:description)";
$params=array(
':user_id' => $current_user['id'],
':file_name'=> $upload_name,
':file_ext'=>$upload_ext,
':description'=>$upload_desc,
);
$result=exec_sql_query($db, $sql, $params);
if ($result){
$file_id=$db->lastInsertId("id");
$new_path="uploads/documents/$file_id.$upload_ext";
move_uploaded_file($upload_info["tmp_name"],$new_path);
}
}
// TODO: If the upload was successful, record the upload in the database
// and permanently store the uploaded file in the uploads directory.
// $box_file=filter_input(INPUT_POST, "box_file", FILTER_SANITIZE_STRING);
// $description=filter_input(INPUT_POST,"description", FILTER_SANITIZE_STRING);
}
?>
<!DOCTYPE html>
<html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Home</title>
<link rel="stylesheet" type="text/css" href="style/all.css" media="all" />
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Ubuntu">
</head>
<body>
<h1>Fine Art Photography</h1>
<div id="content-wrap">
<?php
// If the user is logged in, let them upload files and view their uploaded files.
if ( is_user_logged_in() ) {
foreach ($messages as $message) {
echo "<p><strong>" . htmlspecialchars($message) . "</strong></p>\n";
}
?>
<h2>Upload a File</h2>
<!-- TODO: Peer review this form checking to make sure it properly supports file uploads. -->
<form id="uploadFile" action="index2.php" method="post" enctype="multipart/form-data">
<ul>
<li>
<!-- MAX_FILE_SIZE must precede the file input field -->
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_FILE_SIZE; ?>" />
<label for="box_file">Upload File:</label>
<input id="box_file" type="file" name="box_file">
</li>
<li>
<label for="box_desc">Description:</label>
<textarea id="box_desc" name="description" cols="40" rows="5"></textarea>
</li>
<li>
<button name="submit_upload" type="submit">Upload File</button>
</li>
</ul>
</form>
<?php
} else {
?>
<p><strong>You need to sign in before you can upload image.</strong></p>
<?php
include("includes/login.php");
}
?>
<!-- <h2>Saved Files</h2> -->
<h2>Categories</h2>
<h2>Photos</h2>
<div class="img">
<?php
$records = exec_sql_query($db, "SELECT * FROM images")->fetchAll(PDO::FETCH_ASSOC);
if (count($records) > 0) {
foreach($records as $record) {
echo "<div class=\"content\">";
echo "<div class=\"block\">";
echo "<img class=\"pic\" src=\"uploads/images/". $record["id"] . "." . $record["image_ext"]. "\"/>";
echo "<a href=\"uploads/images/". $record["id"] . "." . $record["image_ext"] .
"\"class=\"link\">" . htmlspecialchars($record["image_name"]) . "</a>";
echo "<p class=\"link\">" . htmlspecialchars($record["description"]). "</p>";
echo "</div>";
echo "</div>";
}
}
?>
</div>
</body>
</html>
And here is my code for init.php:
<?php
// vvv DO NOT MODIFY/REMOVE vvv
// check current php version to ensure it meets 2300's requirements
function check_php_version()
{
if (version_compare(phpversion(), '7.0', '<')) {
define(VERSION_MESSAGE, "PHP version 7.0 or higher is required for 2300. Make sure you have installed PHP 7 on your computer and have set the correct PHP path in VS Code.");
echo VERSION_MESSAGE;
throw VERSION_MESSAGE;
}
}
check_php_version();
function config_php_errors()
{
ini_set('display_startup_errors', 1);
ini_set('display_errors', 0);
error_reporting(E_ALL);
}
config_php_errors();
// open connection to database
function open_or_init_sqlite_db($db_filename, $init_sql_filename)
{
if (!file_exists($db_filename)) {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (file_exists($init_sql_filename)) {
$db_init_sql = file_get_contents($init_sql_filename);
try {
$result = $db->exec($db_init_sql);
if ($result) {
return $db;
}
} catch (PDOException $exception) {
// If we had an error, then the DB did not initialize properly,
// so let's delete it!
unlink($db_filename);
throw $exception;
}
} else {
unlink($db_filename);
}
} else {
$db = new PDO('sqlite:' . $db_filename);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
return null;
}
function exec_sql_query($db, $sql, $params = array())
{
$query = $db->prepare($sql);
if ($query and $query->execute($params)) {
return $query;
}
return null;
}
// ^^^ DO NOT MODIFY/REMOVE ^^^
// You may place any of your code here.
// $db = open_or_init_sqlite_db('secure/site.sqlite', 'secure/init.sql');
define('SESSION_COOKIE_DURATION', 60*60*1);
$session_messages = array();
function log_in($username, $password) {
global $db;
global $current_user;
global $session_messages;
if ( isset($username) && isset($password) ) {
// check if username exists in the database
$sql = "SELECT * FROM users WHERE username = :username;";
$params = array(
':username' => $username
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// There shouldn't be repetitive username.
$account = $records[0];
// Check if password is correct
if ( password_verify($password, $account['password']) ) {
// Create session
$session = session_create_id();
// Store session ID in database
$sql = "INSERT INTO sessions (user_id, session) VALUES (:user_id, :session);";
$params = array(
':user_id' => $account['id'],
':session' => $session
);
$result = exec_sql_query($db, $sql, $params);
if ($result) {
// If result exists, session stored in DB
// Send this back to the user.
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
$current_user = $account;
return $current_user;
} else {
array_push($session_messages, "Log in failed. Something went wrong");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "Invalid username or password.");
}
} else {
array_push($session_messages, "No username or password given.");
}
$current_user = NULL;
return NULL;
}
function find_user($user_id) {
global $db;
$sql = "SELECT * FROM users WHERE id = :user_id;";
$params = array(
':user_id' => $user_id
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// users are unique, there should only be 1 record
return $records[0];
}
return NULL;
}
function find_session($session) {
global $db;
if (isset($session)) {
$sql = "SELECT * FROM sessions WHERE session = :session;";
$params = array(
':session' => $session
);
$records = exec_sql_query($db, $sql, $params)->fetchAll();
if ($records) {
// No repetitive sessions
return $records[0];
}
}
return NULL;
}
function session_login() {
global $db;
global $current_user;
if (isset($_COOKIE["session"])) {
$session = $_COOKIE["session"];
$session_record = find_session($session);
if ( isset($session_record) ) {
$current_user = find_user($session_record['user_id']);
// The session will last for 1 more hour
setcookie("session", $session, time() + SESSION_COOKIE_DURATION);
return $current_user;
}
}
$current_user = NULL;
return NULL;
}
function is_user_logged_in() {
global $current_user;
// if $current_user is not NULL, then a user is logged in.
return ($current_user != NULL);
}
function log_out() {
global $current_user;
// Remove the session from the cookie and fgo back in time to expire the session.
setcookie('session', '', time() - SESSION_COOKIE_DURATION);
$current_user = NULL;
}
// ---- Check for login, logout requests. Or check to keep the user logged in. ----
// Check if we should login the user
if ( isset($_POST['login']) && isset($_POST['username']) && isset($_POST['password']) ) {
$username = trim( $_POST['username'] );
$password = trim( $_POST['password'] );
log_in($username, $password);
} else {
// check if the user already logged in
session_login();
}
// Check if we should logout the user
if ( isset($current_user) && ( isset($_GET['logout']) || isset($_POST['logout']) ) ) {
log_out();
}
?>
Errors
I have written a PHP program which take user new and old password my code is running well but now I have to few lines of code in my PHP program.
This is my code of PHP which I written and I want to add few lines of code in it but when I write new code in it works but it shows new errors, that code which I have to written is warning to user that user "new password should be different with old password". This code warns user when user enter on submit button of new password same as old password webpage.
This is my PHP program:
<?php
session_start();
// if ($_SESSION['user_name'] != "")
// {
// header("location:account.php");
// }
include('connection.php');
// header("Refresh: 20; URL=welcome.php");
// header("Refresh: 20; URL=http://www.stackoverflow.com/");
if(isset($_POST['submit']))
{
$old_password = $_POST['old_password'];
$new_password = $_POST['new_password'];
$query = $con->prepare("select password from tbl_users WHERE id = :user_id");
$query->bindParam(':user_id', $_SESSION['id']);
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->execute();
$fetch = $query->fetch();
$old_pass = $fetch['password'];
if($old_password == $old_pass){
$stmt = $con->prepare("UPDATE tbl_users SET password = (:pass) WHERE id = :user_id");
$stmt->bindParam(':pass', $new_password, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $_SESSION['id']);
// $stmt->execute();
$stmt->execute();
header("location:account.php");
}
else
{
echo "<script>alert('Wrong password! Enter your valid old password')</script>";
}
}
?>
HTML Code:
<!DOCTYPE html>
<html>
<head>
<title>project</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="registration.css">
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<header><h1>Change Password</h1></header>
<form method="post" action="renew.php">
<br />
<input type="password" id="pwd2" placeholder="Enter your old password" name="old_password" required />
<br />
<input type="password" id="pwd1" placeholder="Enter your new password" name="new_password" required />
<center>
<!-- <div class="form-group"> -->
<div id="setPasswordMessage" style="display: none;"></div>
<!-- </div> -->
</center>
<br />
<div class="buttons">
<input type="submit" disabled="submit" class="btn" name="submit" value="Save">
</div>
<br />
</form>
<footer><h3>Copyright © vu.edu.pk (S1701F607E)</h3></footer>
<script type="text/javascript">
$(document).ready(function() {
var pwd1 = $('#pwd1'); //id of first password field
var pwd2 = $('#pwd2'); //id of second password field
var pwdIdSet = $('#setPasswordMessage'); //id of indicator element
setCheckPasswordStrength(pwd1,pwd2,pwdIdSet); //call password check function
});
function setCheckPasswordStrength(pwd1, pwd2, pwdIdSet)
{
/*=========== Start: Set Password Cretria Regular Expression ===================*/
//Password must contain 5 or more characters
var lowPassword = /(?=.{5,}).*/;
//Password must contain at least one digit and lower case letters .
var mediumPassword = /^(?=\S*?[a-z])(?=\S*?[0-9])\S{5,}$/;
//Password must contain at least one digit, one upper case letter and one lower case letter.
var averagePassword = /^(?=\S*?[A-Z])(?=\S*?[a-z])(?=\S*?[0-9])\S{5,}$/;
//Password must contain at least one digit, one upper case letter and one lower case letter.
var strongPassword = /^(?=\S*?[A-Z])(?=\S*?[a-z])(?=\S*?[0-9])(?=\S*?[^\w\*])\S{5,}$/;
/*=========== End: Set Password Cretria Regular Expression ===================*/
// test() method is used to test match in a string whether the value is matched in a string or not.
$(pwd1).on('keyup', function(e) {
var len = $('#pwd1').val().length;
document.getElementById("setPasswordMessage").style.display="block";
if(strongPassword.test(pwd1.val()))
{
pwdIdSet.removeClass().addClass('strongPassword').html("Strong! Please use this password!").css("display","block");
$(':input[type="submit"]').prop('disabled', false);
}
else if(averagePassword.test(pwd1.val()))
{
pwdIdSet.removeClass().addClass('averagePassword').html("Average! Tips: Enter special characters to make even stronger").css("display","block");
$(':input[type="submit"]').prop('disabled', true);
}
else if(mediumPassword.test(pwd1.val()))
{
pwdIdSet.removeClass().addClass('mediumPassword').html("Good! Tips: Enter uppercase letter to make strong").css("display","block");
$(':input[type="submit"]').prop('disabled', true);
}
else if(lowPassword.test(pwd1.val()))
{
pwdIdSet.removeClass().addClass('stilllowPassword').html("Still Weak! Tips: Enter digits to make good password").css("display","block");
$(':input[type="submit"]').prop('disabled', true);
}
else if(len < 1)
{
pwdIdSet.removeClass('lowPassword');
$('#setPasswordMessage').css("display","none");
$(':input[type="submit"]').prop('disabled', true);
}
else
{
pwdIdSet.removeClass().addClass('lowPassword').html("Very Weak! Please use 5 or more chars password)").css("display","block");
$(':input[type="submit"]').prop('disabled', true);
}
});
// $(pwd2).on('keyup', function(e) {
// if(pwd1.val() !== pwd2.val())
// {
// pwdIdSet.removeClass().addClass('lowPassword').html("Passwords do not match!");
// }else{
// pwdIdSet.removeClass().addClass('goodpass').html("Passwords match!");
// }
// });
}
</script>
</body>
</html>
I have to add this code in PHP code but in which place and how.
if($old_password == $new_password)
{
echo "<script>alert('New password should be different with old password')</script>";
}
Put the check right before you do the query.
<?php
session_start();
// if ($_SESSION['user_name'] != "")
// {
// header("location:account.php");
// }
include('connection.php');
// header("Refresh: 20; URL=welcome.php");
// header("Refresh: 20; URL=http://www.stackoverflow.com/");
if(isset($_POST['submit']))
{
$old_password = $_POST['old_password'];
$new_password = $_POST['new_password'];
if ($old_password == $new_password) {
echo "<script>alert('New password should be different with old password')</script>";
} else {
$query = $con->prepare("select password from tbl_users WHERE id = :user_id");
$query->bindParam(':user_id', $_SESSION['id']);
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->execute();
$fetch = $query->fetch();
$old_pass = $fetch['password'];
if($old_password == $old_pass){
$stmt = $con->prepare("UPDATE tbl_users SET password = (:pass) WHERE id = :user_id");
$stmt->bindParam(':pass', $new_password, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $_SESSION['id']);
// $stmt->execute();
$stmt->execute();
header("location:account.php");
}
else
{
echo "<script>alert('Wrong password! Enter your valid old password')</script>";
}
}
}
?>
PHP throws error if header is sent after any output. Thus, if you have any output before header("location:account.php");, an error will occur. Try setting new location via JS instead:
// header("location:account.php");
echo "<script>document.location.href = 'account.php';</script>";
the full code will look something like this:
if($old_password == $old_pass){
if($old_password == $new_password)
{
echo "<script>alert('New password should be different with old password')</script>";
} else {
$stmt = $con->prepare("UPDATE tbl_users SET password = (:pass) WHERE id = :user_id");
$stmt->bindParam(':pass', $new_password, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $_SESSION['id']);
// $stmt->execute();
$stmt->execute();
// header("location:account.php");
echo "<script>document.location.href = 'account.php';</script>";
}
}
else....
You should put this check after you set the variables $old_password and $new_password and before you execute any database queries (you don't want to execute these if old and new password are the same):
if(isset($_POST['submit']))
{
$old_password = $_POST['old_password'];
$new_password = $_POST['new_password'];
if($old_password == $new_password)
{
echo "<script>alert('New password should be different with old password')</script>";
}
else
{
$query = $con->prepare("select password from tbl_users WHERE id = :user_id");
$query->bindParam(':user_id', $_SESSION['id']);
$query->setFetchMode(PDO::FETCH_ASSOC);
$query->execute();
$fetch = $query->fetch();
$old_pass = $fetch['password'];
if($old_password == $old_pass){
$stmt = $con->prepare("UPDATE tbl_users SET password = (:pass) WHERE id = :user_id");
$stmt->bindParam(':pass', $new_password, PDO::PARAM_STR);
$stmt->bindParam(':user_id', $_SESSION['id']);
// $stmt->execute();
$stmt->execute();
header("location:account.php");
}
else
{
echo "<script>alert('Wrong password! Enter your valid old password')</script>";
}
}
}
And while it has nothing to do with coding, I just wanted to note that your error message is not correct English. Something is "different from" something else, not "different with". Use this:
Your new password must be different from your old password
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.
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.
Im trying to set a cookie when the user selects the checkbox to remember his data.
I´m setting cookie and encoding if checkbox is selected:
if($f['save'])
{
$cookiesave = base64_encode($adminEmail).'&'.base64_encode($f['pass']);
setcookie('admin',$cookiesave,time()+60*60*24*30,'/');
}
And then I´m decoding
elseif(!empty($_COOKIE['admin']))
{
$cookie = $_COOKIE['admin'];
$cookie = explode('&',$cookie);
$f['email'] = base64_decode($cookie[0]);
$f['pass'] = base64_decode($cookie[1]);
$f['save'] = 1;
}
But despite being doing the decode, the input appears with encrypted password.
I have reviewed all the code and everything seems to be right ... can see anything wrong?
My full code:
<?php
if(isset($_POST['sendLogin']))
{
$f['email'] = mysql_real_escape_string($_POST['email']);
$f['pass'] = mysql_real_escape_string($_POST['pass']);
$f['save'] = mysql_real_escape_string($_POST['remember']);
$autEmail = $f['email'];
$autSenha = md5($f['pass']);
$readAdmin = read('admins',"WHERE email = '$adminEmail'");
if($readADmin){
foreach($readAdmin as $admin);
if($adminEmail == $admin['email'] && $adminPass == $admin['pass'])
{
if($f['save'])
{
$cookiesave = base64_encode($adminEmail).'&'.base64_encode($f['pass']);
setcookie('admin',$cookiesave,time()+60*60*24*30,'/');
}
else
{
setcookie('admin','',time()+3600,'/');
}
}
else
{
echo 'Wrong Password';
}
}
else
{
echo 'Email dont exist in DB';
}
}
}
elseif(!empty($_COOKIE['admin']))
{
$cookie = $_COOKIE['admin'];
$cookie = explode('&',$cookie);
$f['email'] = base64_decode($cookie[0]);
$f['pass'] = base64_decode($cookie[1]);
$f['save'] = 1;
}
echo '<pre>';
print_r($cookie);
echo
'</pre>';
?>
<?php
if(!isset($_GET['remember']))
{
?>
<form name="login" action="" method="post">
<label>
<span>Email:</span>
<input type="text" class="radius" name="email" value="<?php if(isset($f['email'])) echo $f['email']; ?>" />
</label>
<label>
<span>Password:</span>
<input type="password" class="radius" name="pass" value="<?php if(isset($f['pass'])) echo $f['pass']; ?>" />
</label>
<input type="submit" value="Login" name="sendLogin" class="btn" />
<div class="remember">
<input type="checkbox" name="remember" value="1" <?php if(isset($f['save'])) echo 'checked="checked"' ?> />
Remember Acess data!
</div>
</form>
<?php
}
This is a tested login form (PHP 5.3.18). The comments at the start of the script explains how it works and how to use it.
<?php
/*
* Q22459571
*
* a Login script:
*
* There are three actions it will do:
*
* 1) Display a login screen and process the results
*
* 2) Logout a user who has been 'remembered' or 'saved' see 'admin' cookie.
*
* 3) Automatically login a user from the details in the admin' cookie.
*
* The script action is controlled by a parameter in the URL called 'action'.
*
* The 'action' values and results are as follows:
*
* 1) action='login' : will clear any cookies and force the login screen to be shown
*
* 2) action='logout' : will clear any cookies and exit the script
*
* 3) missing 'action' parameter : a) try and login using the 'admin' cookie.
* b) show the login screen if not
* able to login.
*
* The result of the script will be saved in a '$userAuth' array as follows:
*
* 1) 'email' => user email address as stored on the db.
* 2) 'passhash' => MD5 hash as stored on the database
* 3) 'remember' => boolean to indicate that the user can be logged in
* via the 'admin' cookie
* 4) 'loginMethod' => '', 'cookie', 'form'
* 5) 'loginSuccess'=> true | false
*
*/
/*
* We will use 'mysqli' functions, prepared queries and 'bind' variables/values
*/
/*
* User table:
*
* store password as a 'salted' hash
*
* Columns: 1) email -- unique id for an admin
* 2) passhash -- password as a MD5 hash
* 3) salt -- random string that we will use as a prefix to the plaintext password
* before we take the md5 hash.
*/
// database connection...
$mysqlDb = mysqli_connect('localhost', 'test', 'test', 'testmysql');
// User Authorization details will always be in here...
$userAuth = array( 'email' => '', 'passhash' => '', 'remember' => false,
'loginMethod' => '', 'loginSuccess' => false);
// set the login action so we can use it later
$loginAction = isset($_GET['action']) ? $_GET['action'] : '';
/*
* see what the URL action is
*/
if ($loginAction == 'logout')
{
setcookie('admin', '' , 0, '/'); // delete cookie
echo 'user logged out'; // do what you wish here
exit; // leave the script
}
if ($loginAction == 'login')
{
if (!empty($_COOKIE['admin'])) // clear the cookie to force login
{
setcookie('admin', '' , time() + 3600, '/'); // will be empty next time
}
}
elseif (!empty($_COOKIE['admin'])) // The cookie should be encrypted -- not in this version.
{
$cookie = $_COOKIE['admin'];
$emailLen = substr($cookie, 0, 3); // get the length
$b64 = substr($cookie, 3); // get b64 encoded string
$b64decoded = base64_decode($b64); // convert back to original string
// split it up...
$userAuth['email'] = substr($b64decoded, 0, $emailLen);
$userAuth['passhash'] = substr($b64decoded, $emailLen);
$userAuth['remember' ] = 1;
// ensure user is in the database and the details match...
$sql = 'SELECT email, salt from admins WHERE email = ? and passhash = ? limit 1';
$query = mysqli_prepare($mysqlDb, $sql);
$allOk = mysqli_stmt_bind_param($query, 'ss', $userAuth['email'], $userAuth['passhash']);
$allOk = mysqli_execute($query);
$queryResult = mysqli_stmt_get_result($query);
$admin = mysqli_fetch_array($queryResult);
$userAuth['loginMethod'] = 'cookie';
$userAuth['loginSuccess'] = !empty($admin['email'])
&& $admin['email'] === $userAuth['email'];
if ($userAuth['loginSuccess'])
{
echo 'user: ', $userAuth['email'], ' was logged in via the cookie...';
exit;
}
else
{
echo 'user: ', $userAuth['email'], ' cookie details are wrong!!';
exit;
}
}
/*
* We may have a login request that we need to check...
*/
if (isset($_POST['sendLogin'])) // new login attempt
{
$userAuth['loginMethod'] = 'form';
$userAuth['loginSuccess'] = false;
$userAuth['email'] = mysqli_real_escape_string($mysqlDb, $_POST['email']);
$userPass = mysqli_real_escape_string($mysqlDb, $_POST['pass']);
$userAuth['remember'] = mysqli_real_escape_string($mysqlDb, $_POST['remember']);
// will use prepared queries and bind parameters as required
$sql = 'SELECT email, passhash, salt from admins WHERE email = ? limit 1';
$query = mysqli_prepare($mysqlDb, $sql);
$allOk = mysqli_stmt_bind_param($query, 's', $userAuth['email']);
$allOk = mysqli_execute($query);
$queryResult = mysqli_stmt_get_result($query);
$admin = mysqli_fetch_array($queryResult); // admin details
if ( !empty($userAuth['email']) && $userAuth['email'] == $admin['email']
&& !empty($userPass))
{
// calculate the MD5 hash and assume it is ok
$userAuth['passhash'] = md5($admin['salt'] . $userPass);
}
if (!empty($userAuth['passhash']) && $userAuth['passhash'] === $admin['passhash']) // passwords must have matched
{
$userAuth['loginSuccess'] = true;
if ($userAuth['remember' ])
{
$emailLen = sprintf('%03u', strlen($userAuth['email']));
$cookiesave = $emailLen . base64_encode($userAuth['email'] . $userAuth['passhash']);
setcookie('admin', $cookiesave, time() + 60 * 60 * 24 * 30, '/');
}
else
{
setcookie('admin', '' , 0, '/'); // delete cookie
}
}
else
{
setcookie('admin', '' , 0, '/'); // delete cookie if unsuccessful login
echo 'Wrong Email / Password or both';
}
} // end of form login
// if successful login
if ($userAuth['loginSuccess'])
{
echo 'user: ', $userAuth['email'], ' is logged in via: ', $userAuth['loginMethod'];
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Enter Login Details</title>
</head>
<body>
<form name="login" action="/testmysql/Q22459571_cookie_base64.php
" method="post">
<label>
<span>Email:</span>
<input type="text" class="radius" name="email" value="<?php echo $userAuth['email']; ?>" />
</label>
<label>
<span>Password:</span>
<input type="password" class="radius" name="pass" value="" />
</label>
<div class="remember">
<input type="checkbox" id="remember" name="remember" value="1" <?php echo 'checked="checked"' ?> />
<label for="remember">Remember Me!</label>
</div>
<input type="submit" value="Login" name="sendLogin" class="btn" />
</form>
</body>
</html>