prepare("SELECT id, username, type, password, salt FROM members WHERE email = ? LIMIT 1")) { $stmt->bind_param('s', $email); // Bind "$email" to parameter. $stmt->execute(); // Execute the prepared query. $stmt->store_result(); // get variables from result. $stmt->bind_result($user_id, $username, $type, $db_password, $salt); $stmt->fetch(); // hash the password with the unique salt. $password = hash('sha512', $password . $salt); if ($stmt->num_rows == 1) { // If the user exists we check if the account is locked // from too many login attempts if (checkbrute($user_id, $mysqli) == true) { // Account is locked // TODO ADD CODE TO Send an email to user saying their account is locked return "Account locked"; } else { // Check if the password in the database matches // the password the user submitted. if ($db_password == $password) { // Password is correct! Login is successfull // Update last login timestamp. $con=mysqli_connect("127.0.0.1","root","Land6k","Components"); if (mysqli_connect_errno()) { return "Failed to connect to MySQL: " . mysqli_connect_error(); } $query="UPDATE members SET last_login=now() WHERE id='" . $user_id . "'"; $result = mysqli_query($con,$query); if (!$result) // Oooh, If not correct then bail out return "Timestamp error! (" . $query . ")"; else { // Get the user-agent string of the user. $user_browser = $_SERVER['HTTP_USER_AGENT']; // XSS protection as we might print this value $user_id = preg_replace("/[^0-9]+/", "", $user_id); $_SESSION['user_id'] = $user_id; // XSS protection as we might print this value $username = preg_replace("/[^a-zA-Z0-9_\-]+/","",$username); $_SESSION['username'] = $username; // XSS protection as we might print this value $username = preg_replace("/[^a-zA-Z0-9_\-]+/","",$type); $_SESSION['type'] = $type; $_SESSION['login_string'] = hash('sha512', $password . $user_browser); $_SESSION['timestamp'] = time(); return "OK"; } } else { // Password is not correct // We record this attempt in the database $now = time(); $mysqli->query("INSERT INTO login_attempts(user_id, time) VALUES ('$user_id', '$now')"); return "Unknown userid or password"; } } } else { // No user exists. return "Unknown userid or password"; } } } function checkbrute($user_id, $mysqli) { // Get timestamp of current time $now = time(); // All login attempts are counted from the past 2 hours. $valid_attempts = $now - (2 * 60 * 60); if ($stmt = $mysqli->prepare("SELECT time FROM login_attempts
                             WHERE user_id = ?
                            AND time > '$valid_attempts'")) {
        $stmt->bind_param('i', $user_id);

        // Execute the prepared query.
        $stmt->execute();
        $stmt->store_result();

        // If there have been more than 5 failed logins
        if ($stmt->num_rows > 5) {
            return true;
        } else {
            return false;
        }
    }
}

function login_check($mysqli) {
	$user_id = $_SESSION['user_id'];
	$login_string = $_SESSION['login_string'];
	$username = $_SESSION['username'];

  // Check if all session variables are set
  if (isset($user_id, $login_string, $username))
	{
        // Get the user-agent string of the user.
        $user_browser = $_SERVER['HTTP_USER_AGENT'];

        if ($stmt = $mysqli->prepare("SELECT password
                                      FROM members
                                      WHERE id = ? LIMIT 1")) {
            // Bind "$user_id" to parameter.
            $stmt->bind_param('i', $user_id);
            $stmt->execute();   // Execute the prepared query.
            $stmt->store_result();

            if ($stmt->num_rows == 1) {
                // If the user exists get variables from result.
                $stmt->bind_result($password);
                $stmt->fetch();

								// TODO : ADD CODE TO CHECK FOR TIMEOUT
								// Add a field in the database holding time for last activity (i.e. last time this function was called)
								// Compare with time now and return false if time is, say.... 30 min or so.
								// If false occure also remove coockie
								// Else continue to the if below.

                $login_check = hash('sha512', $password . $user_browser);
                if ($login_check == $login_string) {
                    // Logged In!!!!

                    // TODO Update active timer in database

                    return true;
                } else {
                    // Not logged in
                    return false;
                }
            } else {
                // Not logged in
                return false;
            }
        } else {
            // Not logged in
            return false;
        }
    } else {
        // Not logged in
        return false;
    }
}

function esc_url($url) {

    if ('' == $url) {
        return $url;
    }

    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);

    $strip = array('%0d', '%0a', '%0D', '%0A');
    $url = (string) $url;

    $count = 1;
    while ($count) {
        $url = str_replace($strip, '', $url, $count);
    }

    $url = str_replace(';//', '://', $url);

    $url = htmlentities($url);

    $url = str_replace('&', '&', $url);
    $url = str_replace("'", ''', $url);

    if ($url[0] !== '/') {
        // We're only interested in relative links from $_SERVER['PHP_SELF']
        return '';
    } else {
        return $url;
    }
}

// Function for backing up tables in a database, table by table
// $tables may be set to wanted table or * to backup all
function backup_tables($host,$user,$pass,$name,$tables = '*',$filename)
{
	$link = mysql_connect($host,$user,$pass);
	// Check connection
	if ($err=mysqli_connect_errno())
  		header('Location: ./call.php?target=error&error=' . $err);

	mysql_select_db($name,$link);

	//get the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysql_query('SHOW TABLES');

		if ($result==FALSE)
			return $filename=FALSE;

		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}

	//cycle through
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM '.$table);

		if ($result==FALSE)
			return $filename=FALSE;

		$num_fields = mysql_num_fields($result);

		$return.= 'DROP TABLE '.$table.';';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));

		$return.= "\n\n".$row2[1].";\n\n";

		for ($i = 0; $i < $num_fields; $i++)
		{
			while($row = mysql_fetch_row($result))
			{
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j<$num_fields; $j++)
				{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = ereg_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}

	//save file.
	$filename = $filename . time().'-'.(md5(implode(',',$tables))).'.sql';

	$handle = fopen($filename,'w+');
	fwrite($handle,$return);
	fclose($handle);

	return $filename;
}
?>