I’m ripping my noob hair out here. Can’t understand why below code isn’t working. The page loads alright, but when I try to log in with the username and password that is in my database the page is just reloaded to its original state with the login form, when I’d actually like to see a logout button instead. I’ve also tried comparing the password without salt and hash with an unhashed, unsalted equivalent in the database. Not working.
The only warnings I get are “It is not safe to rely on the system’s timezone settings.”, and I don’t think those have anything to do with the password verification functionality.
The page starts out like this:
session_start();
error_reporting(-1); ini_set('display_errors', 'On');
Then follows some HTML. Then:
if (isset($_POST['log_out'])) {
session_unset();
session_destroy();
$_SESSION = array();
}
The logout button, when pressed, sets $_POST['log_out']. Then comes a function I got from a book, used to prevent SQL injection:
function mysql_fix_string($string) {
if (get_magic_quotes_gpc()) $string = stripslashes($string);
$string = htmlspecialchars($string, ENT_QUOTES);
$string = mysql_real_escape_string($string);
return $string;
}
Then comes the password verification part, which should only run if the user has submitted the login form (which posts back to the same page, thus setting $_POST['username'] and $_POST['password']):
if (isset($_POST['username']) && isset($_POST['password'])) {
$salt1 = 'how';
$salt2 = 'pony';
$password = md5($salt1 . $_POST['password'] . $salt2);
$db_hostname = 'xxxxxxxxx';
$db_username = 'xxxxxxxxx';
$db_password = 'xxxxxxxxx';
$db_database = 'xxxxxxxxx';
$db_server = mysql_connect($db_hostname, $db_username, $db_password);
if (!$db_server) die("Unable to connect to MySQL: " . mysql_error());
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
$username = mysql_fix_string($_POST['username']);
$query = "SELECT password FROM users WHERE name = '" . $username . "'";
$result = mysql_fetch_assoc($query);
$passwordindatabase = $result['password'];
if ($password == $passwordindatabase) {
$_SESSION['logged_in'] = true;
$_SESSION['user'] = $username;
unset($_POST['username']);
unset($_POST['password']);
}
}
A bit further down comes the login form, only shown if ($_SESSION['logged_in'] != true). It posts the values of the input fields username and password to $_SERVER['REQUEST_URI'] (the same page).
Looks to me like you’re missing the mysql_query() function which means you aren’t actually executing the query.
Do the following and see if it works:
Edit
On a completely different note, you should not use mysql functions since they are quite old fashioned and have mysql_injection vulnerability. I would advice you to start working with PDO as soon as possible, which (if done right) has got no mysql_injection vulerabilities.