Log in tutorials

firstly my apologies if (when) this post breaks the forum rules.....
secondly, yes I have used google and the forum search but I'm not 100% sure what I'm looking for.

I am looking for a log in tutorial (using PHP/MySQL) that is aimed at the n00b (with a basic knowledge of php), that gives code examples (they don't have to be production examples) but more importantly explains what each part does, in effect teaching me instead of just doing it for me.

A registration system is not really needed because it will be for a small closed community so that can easily be done manually.

The reason for being logged in to this site would be to have a private section for discussion and the ability to upload photos etc to a public part of the site. (the tut need not cover this)

Everything I have found so far is either dated, unsuitable or doesn't offer decent explanations of what is being done.

//initialize an empty "error" variable so you don't get a PHP warning later when you try to use it:
$error = '';

//if $_POST['submit'] is set, that means the user attempted to log in:
if ( isset($_POST['submit']) ) {
//the form was submitted, but make sure the username and password aren't blank:
if ( empty( $_POST['user'] ) || empty( $_POST['pass'] ) ) {
$error = 'Please fill out a username and password';
} else {
/*username and password are set, attempt to see if the user exists and the login is correct.
we do this by simply selecting from the table where the username and password match the inputs.
Note two things:
1) We are using crypt() with a salt to determine the password. Your registration form should
create the user's initial password with the SAME METHOD. YOU MUST USE THIS METHOD TO CREATE USERS
2) We wrap all plaintext user input (the username in this case) with mysql_real_escape_string.
This prevents SQL injection attacks.
*/
$sql = "SELECT id, loginCount, lastLogin FROM users WHERE username = '" . mysql_real_escape_string($_POST['user']) . "' AND password = '" .
crypt($_POST['pass'], 'abc123SomeSalt321cba') . "'";
//now execute the SQL query and store the results to a variable:
$rs = mysql_query( $sql );

//if $rs is false, we encountered an error. My query is soundly written, but error handling is ALWAYS a good idea
if ( $rs === false ) {
//It is always a good idea to write a custom error handler that will handle your errors, email you the problem,
//log the problem to the filesystem, and show the user a GENERIC non-specific "oops" page. For a beginner,
//simply dying with the error is enough for you, but NEVER do this in production, it reveals your database structure
die("An unexpected error occurred!<br />" . mysql_error() . "<br />For the query:<br />" . $sql);
}
//$rs is not false, but did it return a row...?
elseif ( mysql_num_rows( $rs ) == 0 ) {
//no rows returned, either the user doesn't exist or their password is bad. DO NOT TELL THEM which condition occurred.
//If you make an error that says "that user is ok, but the password is wrong" people can build a list of your users.
$error = 'Invalid username/password combination, please try again.';
} else {
//If we've arrived here, the query was valid and returned a row:
$row = mysql_fetch_array($rs);
$_SESSION['loggedIn'] = true;
$_SESSION['userId'] = $row['id'];
$_SESSION['username'] = $_POST['user'];
$_SESSION['loginCount'] = $row['loginCount'];
$_SESSION['lastLogin'] = $row['lastLogin'];
//never store the password anywhere.

//update the two bits of metadata on the user page. This is not really necessary for a basic login system,
//but it's fun and cool and gives you a good idea of how to do such things:
mysql_query("UPDATE users SET loginCount = loginCount+1, lastLogin = NOW() WHERE userId = {$row['id']}");
//no error handling here. Should you write some? What should it do? Left up to the reader.

//redirect the user to a "thank you for logging in" page, or to the member page, or whatever:
header("Location: someFile.php");
die(); //always die after a header call, always
}
}
} else {
//$_POST['submit'] is not set, so the form is not submitted. simply print the form:
?>
<!-- if no form action is set, it will post to the same page, which is what we want -->
<form method="POST">
<table cellpadding=5>
<tr>
<!-- This row contains a single cell that spans two columns and will show the PHP error if there is one. -->
<th colspan="2">
<span style="font-weight: bold; color: red;"><?php echo $error; ?></span>
</th>
</tr>
<tr>
<td>Username</td>
<!-- The PHP syntax you see here is called the ternary operator. It's a one-line IF-THEN check, in the format:
condition ? if-true : if-false; You check a condition (our isset check), and if it's true, you use the value
from if-true. If the condition is false, you use the if-false value. In this way we can say "if $_POST['user']
is set, use it as the value for this cell, otherwise use nothing." -->
<td><input type="text" name="user" value="<?php echo isset($_POST['user']) ? $_POST['user'] : ""; ?>" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" value="" /></td>
</tr>
<tr>
<th colspan="2"><input type="submit" name="submit" /></th>
</tr>
</table>
</form>

<?php
//close the bracket for the last "else" in the PHP
}

/*Further notes/usage examples. THE FOLLOWING IS NOT PART OF THIS SCRIPT*/

//Any page which uses login information (all of them, hopefully) needs this line:
session_start();
//This line is necessary to access the session, which is where we stored the login information.
//It's a good idea to simply put session_start at the top of your general includes.php or whatever.

//To check to see if a user is logged in to a page:
if ( isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] === true ) {
//the user is logged in
}

//You may continue to manipulate the session in any way you see fit, but note that it's super-global.
//If you overwrite userId or clear the session or destroy the sesion cookie, they will be logged out.
//They will also be logged out when they close their browser window.

Well written, and simple. I really appreciate that you introduced some secruity giving me a place to start researching as that was my next on my list. I'm having a problem with the script that I cannot figure out though. I've fiddle with it but can't seem to come up with anything.

Somethings wrong with the first bit of code, $rs isn't get a value for somereason. I have the rest of the code commented out as I figured out where the problem was occuring but I'm getting nothing returned, not even an error. Alas I have no idea what's wrong.

edit: Guh, the code block thing on this forum takes away all the formatting, I fixed the part thats wrong to be readle, I have the rest commented out at anyway.

Welcome to the forum. Please re-post your code by pasting it into the big box, then highlighting it and clicking the "PHP" button. The way you've done it now forces it all on the same line and I cannot read any of it.

Welcome to the forum. Please re-post your code by pasting it into the big box, then highlighting it and clicking the "PHP" button. The way you've done it now forces it all on the same line and I cannot read any of it.

Thanks for the welcome and directing me here from phpfreaks. The code is now formatted.