<?php # Script 12.2 - login_functions
// This page defines two functions used by the login/logout process.
// /* MOVED TO MAIN FUNCTION FILE FOR SITE WIDE USE
// * This function determines an absolute URL and redirects the user there.
// * The function takes one argument: the page to be redirected to.
// * The argument defaults to the login form of chapter 12.
// */
function redirect_user ($page = 'index.php?chapter=12&script=12.5&path=using+cookies') {
// Start defining the URL...
// URL is http:// plus the host name plus the current directory:
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
// Remove any trailing slashes:
$url = rtrim($url, '/\\');
// Add the page:
$url .= '/' . $page;
// Redirect the user:
header("Location: $url");
exit(); // Quit the script.
} // End of redirect_user() function.
/* This function validates the forum login form data (the username and password).
* If both are present, the database is queried.
* The function requires a database connection.
* The function returns an array of information, including:
* - a TRUE/FALSE variable indicating success
* - an array of either errors or the database result
*/
function check_forum_login($link, $user_name = '', $pass = '') {
$errors = array(); // Initialize error array.
// Validate the username
if (empty($user_name)) {
$errors['un'] = 'Please enter a user name.';
} else {
$user_name = mysqli_real_escape_string($link, trim($user_name));
}
// Validate the password:
if (empty($pass)) {
$errors['p'] = 'Please enter your password.';
} else {
$p = mysqli_real_escape_string($link, trim($pass));
}
if (empty($errors)) { // If everything's OK.
// Retrieve the user_id and first_name for that email/password combination:
$q = "SELECT user_id, lang_id, username, time_zone FROM mb_users WHERE username='$user_name' AND pass=SHA1('$p')";
$r = @mysqli_query ($link, $q); // Run the query.
// Check the result:
if (mysqli_num_rows($r) == 1) {
// Fetch the record:
$row = mysqli_fetch_array ($r, MYSQLI_ASSOC);
// Return true and the record:
return array(true, $row);
} else { // Not a match!
$errors['m'] = 'The user name and password entered do not match those on file.';
}
} // End of empty($errors) IF.
// Return false and the errors:
return array(false, $errors);
} // End of check_login() function.