PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
<?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;
}
}
?>
Something like that for the first page, and on secure pages where a user is required to be logged in, you can simply do
if (!$_SESSION['loggedin']) {
exit('User is not logged in!');
}
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.
Thanks a ton! I'll get to modifying that code now. Also, I need to pull the variable "username" from the session and make changes to the user's row on subsequent pages. How do I do that?
login.php is a seperate page, no frames, and links to start.php once the user logs in
start.php is the above code. The first frame on that page loads source.php, the lower frame loads the website as chosen by the php script run on start.php
Get this.... my script works perfectly in Internet Explorer.
I did a bunch of research on this, and here's what I found:
It seems to be a problem with FireFox and using frames. The sessions ends (aparently) when using a frame. This problem does not exist in IE. I'll look for a solution and I'll post it here if/when I find it. If anyone knows of a solution already, please let me know