Right now I'm creating a community. You can register and create your own profile and post on a forum etc. I'm just doing this for fun and learning. I'm not planning on becoming a professional programmer this is just a hobby of mine.
Anyway, I want do it right though. Please review my script and tell me if it seems OK and safe. And please if you have a suggestion or anything go ahead.
This is the login (I use sessions):
// Trim values sent from form
$username = trim($_POST['username']);
$password = trim($_POST['password']);
// Get user info and their rights matching login attempt
$stmt = $db->prepare("SELECT id, username, g_can_delete_users, g_can_edit_post, g_can_handle_reports FROM users LEFT JOIN groups ON groups.g_id = users.group_id WHERE users.username = ? AND SHA1(CONCAT(users.salt, ?)) = users.password");
$stmt->execute(array($username, $password));
$row = $stmt->fetch();
// Did we find a match?
if ($row) {
$_SESSION['user'] = $row;
header("Location: index.php");
exit;
} else {
header("Location: index.php");
exit;
}
And the registration part:
// Example of a generated salt: &O93Wrl`x#iY
$username = trim($_POST['username']);
$email = strtolower(trim($_POST['email']));
$password1 = trim($_POST['password1']);
$password2 = trim($_POST['password2']);
// Validate the username
if (strlen($username) < 4)
$errors[] = "Username must be at least 4 characters.";
// ... and the password
else if (strlen($password1) < 4)
$errors[] = "Password too short";
else if ($password1 != $password2)
$errors[] = "Passwords do not match";
else
$stmt = $db->prepare("INSERT INTO users (username, password, email, salt, registered, registration_ip) VALUES (:username, :password, :email, :salt, :registered, :registration_ip)");
$stmt->execute(array(':username'=>$username, ':password'=>sha1($salt.$password1), ':email'=>$email, ':salt'=>$gen_salt, ':registered'=>time(), ':registration_ip'=>$_SERVER['REMOTE_ADDR']));