Posted: Fri Mar 17, 2006 2:21 pm
here are some improvements and comments
Something like that for the first page, and on secure pages where a user is required to be logged in, you can simply do
or at the top of a page
and if $_SESSION['loggedin'] anything below this if statement will not be parsed. It is much safer to have a flag 'loggedin' instead of storing the password in a session.
Code: Select all
<?php
// Don't rely on submit button to be pressed since pressing enter will submit the form
// without the submit button
if(!empty($_POST['username']) && !empty($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
// Only connect to db if we need to do a lookup
mysql_connect ("localhost", "xxx", "xxx") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("xxx");
// We use mysql_real_escape_string to avoid anything malicious being injected into the query string
$sql = 'SELECT * FROM `accounts` WHERE `name` = \''.mysql_real_escape_string($username).'\' '.
'AND `passworddb` = \''.mysql_real_escape_string($password).'\' LIMIT 1';
$result = mysql_query($sql) or die(mysql_error());
// mysql_num_rows() returns an int, so we check for an int by not using a quote (which parses as a string)
if (mysql_num_rows($result) == 1) {
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
}
}
?>Code: Select all
if ($_SESSION['loggedin']) {
// user is logged in show some secure stuff
}Code: Select all
if (!$_SESSION['loggedin']) {
exit('User is not logged in!');
}