I am fairly new to PHP, and I am going through a book on it. One aspect is about creating a login system. I have copes it exactly from the book but it is not working when I implement it onto my own server. Was wondering if you guys could help shed some light onto it.
When someone logs in, the 2 variables are carried from the form to this page:
<?php
// include function files for this application
require_once('bookmark_fns.php');
session_start();
//create short variable names
$username = $_POST['username'];
$passwd = $_POST['passwd'];
if ($username && $passwd) {
// they have just tried logging in
try {
login($username, $passwd);
// if they are in the database register the user id
$_SESSION['valid_user'] = $username;
}
catch(Exception $e) {
// unsuccessful login
do_html_header('Problem:');
echo 'You could not be logged in.
You must be logged in to view this page.';
do_html_url('login.php', 'Login');
do_html_footer();
exit;
}
}
do_html_header('Home');
check_valid_user();
// get the bookmarks this user has saved
if ($url_array = get_user_urls($_SESSION['valid_user'])) {
display_user_urls($url_array);
}
// give menu of options
display_user_menu();
do_html_footer();
?>
The main part id the first half. When I try it I keep getting the exception message listed here of "'You could not be logged in. You must be logged in to view this page".
The login function it is referencing is:
function login($username, $password) {
// check username and password with db
// if yes, return true
// else throw exception
// connect to db
$conn = db_connect();
// check if username is unique
$result = $conn->query("select * from user
where username='".$username."'
and passwd = sha1('".$password."')");
if (!$result) {
throw new Exception('Could not log you in.');
}
if ($result->num_rows>0) {
return true;
} else {
throw new Exception('Could not log you in.');
}
}
Does anyone know why it would still not be letting me log in? The names are definitely in the database. It is definitely connecting to the database, (as when I use the db_connect function to register users, its works fine). I have coped the source code over from the actual CD just to make sure it is perfect, and it is still doing this. Is there any sort of php update that has happened recently that would make this code not work anymore? I am thinking maybe the "try" function has changed, as I cant find much of it on phpmanual.
Cheers.