Ok, so you’re basically going to have to actually change your code base because the codes that I am about to post uses up-to-date codes.
What it uses
- password_verify
- Checks to see if both session and cookie are the same. (Adopted from Facebook). ← I’ve personally tested this on Facebook and it works. It basically checks to see if the cookie is modified. If it has been modified, the user gets logged off right away. This is to prevent users from logging into someone else’s account by exploiting the cookies.
db.php
<?php
/*
In this part, you check whether the PHP version is between 5.2 and 5.4.
*/
if((PHP_VERSION > '5.2' && PHP_VERSION < '5.4')) {
// Since your PHP version is between 5.2 and 5.4, you can use session_id() to check if sessions already have been started.
if(session_id() == '') {
session_start(); // Start the session since the session hasn't been started
}
} elseif((PHP_VERSION >= '5.4')) {
// Since your PHP version is 5.4 and above, you can use session_status as it is only available for 5.4 and higher.
if(session_status() == PHP_SESSION_NONE) {
session_start(); // Start the session since the session hasn't been started
}
}
/*
End the top notice here
*/
// Use mysqli_report to report where exactly has the code gone wrong whether it'd be a typo trying to find a user
// Or maybe even a non-existing table.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$host = "127.0.0.1";
$user = "root";
$pass = "root";
$db = "xperia";
try {
$connection = new mysqli($host, $user, $pass, $db); // Your connection is good
} catch(mysqli_sql_exception $e) {
throw $e; // Basically print the error
}
if(file_exists('password_hash.php')) {
require('password_hash.php'); // require the alternative PHP password_hash file.
} else {
print('You are missing the password_hash.php file. <a href="https://github.com/ircmaxell/password_compat/tree/master/lib" target="_new">Click here</a> to download it. Rename the file password.php to password_hash.php.');
die();
}
index.php
<?php
require('db.php');
// Check to see if the session userid exists.
if(!isset($_SESSION['userid'])) {
header('Location: login.php'); // Since the session userid doesn't exist, redirect them back to the login page.
die(); // Ignore anything after this. Redundant, but trying to be safe here.
} else {
// Check to see if the cookie some_cookie_thing exists
if(isset($_COOKIE['some_cookie_thing'])) {
// If it exists, that's good.
// Check to see if the session userid and some_cookie_thing are equaled.
if($_SESSION['userid'] == $_COOKIE['some_cookie_thing']) {
// If you some how reach to this point, that means that the session userid exists
// And the cookie some_cookie_thing has not been modified yet.
$id = filter_var($_SESSION['userid'], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); // Append the session userid a variable.
$mysqli = $connection->prepare("SELECT id, username, password FROM xperia WHERE id = ?"); // SQL query string
$mysqli->bind_param('i', $id); // Bind the userid to avoid SQL Injections.
$mysqli->execute(); // Execute the query
$mysqli->store_result(); // Store the result for later checking
if($mysqli->num_rows) {
$mysqli->bind_result($id, $username, $password); // Bind and append variables to the columns
// Make a while loop to fetch the data
while($mysqli->fetch()) {
?>
<!DOCTYPE HTML>
<html>
<p><?php print($username); ?></p>
</html>
<?php
}
} else {
// Since the query line didn't return anything.
// Unset the session userid and redirect the user back to the login page.
// Unset the session userid and cookie some_cookie_thing if they exit.
if(isset($_SESSION['userid'])) {
unset($_SESSION['userid']);
}
if(isset($_COOKIE['some_cookie_thing'])) {
setcookie('some_cookie_thing', '', time() - 3600, '/', $_SERVER['SERVER_NAME'], isset($_SERVER['HTTPS']), true);
}
header('Location: login.php');
die();
}
} else {
// Since the session userid and the cookie some_cookie_thing didn't equal to each other,
// Most likely the user has used a 3rd party program to modify their cookies.
// Unset the session userid and cookie some_cookie_thing if they exit.
if(isset($_SESSION['userid'])) {
unset($_SESSION['userid']);
}
if(isset($_COOKIE['some_cookie_thing'])) {
setcookie('some_cookie_thing', '', time() - 3600, '/', $_SERVER['SERVER_NAME'], isset($_SERVER['HTTPS']), true);
}
header('Location: login.php');
die();
}
} else {
// Since the session userid doesn't exist
// Unset the session userid and cookie some_cookie_thing if they exit
// And redirect the user to the login page.
if(isset($_SESSION['userid'])) {
unset($_SESSION['userid']);
}
if(isset($_COOKIE['some_cookie_thing'])) {
setcookie('some_cookie_thing', '', time() - 3600, '/', $_SERVER['SERVER_NAME'], isset($_SERVER['HTTPS']), true);
}
header('Location: login.php');
die();
}
}
login.php
<?php
require('db.php'); // Require the DB file
// Check to see if session userid exists first
if(isset($_SESSION['userid'])) {
header('Location: index.php'); // Since the session userid exists, redirect them back to the index page.
die(); // Ignore anything after this. Redundant, but trying to be safe here.
} else {
// As said in my original post, using isset($_POST['submit']) is an amateur move
// And will fail when the user hits the "Enter" key on their keyboard on a random text box.
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if($_POST['username'] == '') {
// Check to see if the username field is empty
// If so, give them the first error.
$_SESSION['error'] = 1; // Username was not typed in.
header('Location: login.php'); // Redirect them back to the login page.
die(); // Ignore anything after this. Redundant, but trying to be safe here.
} elseif($_POST['password'] == '') {
// Check to see if the password field is empty
// If so, give them the second error.
$_SESSION['error'] = 2; // Password was not typed in.
// However check to see if the username was typed in
if($_POST['username'] != '') {
$_SESSION['usename'] = $_POST['username']; // If so, set the session usename to the posted username
}
header('Location: login.php'); // Redirect them back to the login page.
die(); // Ignore anything after this. Redundant, but trying to be safe here.
} else {
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); // FIlter the username so no bad characters are in here.
$username = trim($username); // Trim the username so that there aren't any spaces in the username
$password = $_POST['password']; // Don't EVER EVER EVER EVER modify or touch the user's input password whether you "think" it's safe or not.
$mysqli = $connection->prepare("SELECT id, username, password FROM xperia WHERE username = ?"); // Your query string
$mysqli->bind_param('s', $username); // Bind the posted username to the query string to avoid SQL Injection.
$mysqli->execute(); // Execute the query line
$mysqli->store_result(); // Store the result for later checking
// Check to see if the query line returns a
if($mysqli->num_rows) {
$mysqli->bind_result($id, $username, $get_password); // Bind and append variables to the columns
// Make a while loop to fetch the data
while($mysqli->fetch()) {
// Use PHP's default password_verify to verify whether the passwords match or not
if(password_verify($password, $get_password)) {
setcookie('some_cookie_thing', $id, 0, '/', $_SERVER['SERVER_NAME'], isset($_SERVER['HTTPS']), true); // a cookie on the current domain
$_SESSION['userid'] = $id; // Set the session userid as the ID of the current user.
header('Location: index.php'); // Redirect them back to the index page.
die(); // Ignore anything after this. Redundant, but trying to be safe here.
} else {
$_SESSION['error'] = 3; // The account exists, but the password was typed in wrong.
$_SESSION['usename'] = $_POST['username']; // Set
header('Location: login.php'); // Redirect them back to the login page.
die(); // Ignore anything after this. Redundant, but trying to be safe here.
}
}
} else {
$_SESSION['error'] = 4; // The account really doesn't exist in the database.
header('Location: login.php'); // Redirect them back to the login page.
die(); // Ignore anything after this. Redundant, but trying to be safe here.
}
}
}
?>
<!DOCTYPE HTML>
<html>
<?php
// Show a customized error to the user.
if(isset($_SESSION['error'])) {
if($_SESSION['error'] == 1) {
?>
<p>Username not typed in.</p>
<?php
} elseif($_SESSION['error'] == 2) {
?>
<p>Password not typed in.</p>
<?php
} elseif($_SESSION['error'] == 3) {
?>
<p>Your username or password is not correct.</p>
<?php
} elseif($_SESSION['error'] == 4) {
?>
<p>Your account does not exist.</p>
<?php
}
}
?>
<form action = "login.php" method = "POST" >
<tr>
<td><input type = "text" name = "username" value = "<?php if(isset($_SESSION['usename'])) { print($_SESSION['usename']); } ?>" /></td>
</tr>
<tr>
<td><input type = "password" name = "password" value = "" /></td>
</tr>
<input type="submit" name="submit" value="Submit"/>
</form>
</html>
<?php
if(isset($_SESSION['error'])) {
// If session error exists, unset it so when the user comes back to the same page and does something different.
// They will be prompt a new error instead of the same error.
unset($_SESSION['error']);
}
if(isset($_SESSION['usename'])) {
// If session usename exists, unset it since it is a temporary session.
// They will be prompt a new username if they mess up again with a new username.
unset($_SESSION['usename']);
}
}
NOTE:
Please take note that these logic are bad because we are nesting HTML codes within PHP codes. It is ideal to save the HTML part in a separate file and require it from the PHP files. Also, you don’t have to use these codes if you don’t want to. I won’t be forcing you to.
If you find an error some where, let me know.