Well, with what you were thinking of doing you would get the username/password each time in order to validate their login. And yes, you would just include the file user_auth.php and then run the function.
Sessions would be your best bet (or cookies if you want, same type of handeling). Basically, you would check to see if they're logged in. So you run your query, and then mySQL either comes back with 1 or 0 rows. Then, if it comes back with 1 row, you set a session var and then check that through each page. If no rows come back, you unset/clear the session var AND destroy the session.
Then the logout page just destroys the session!!
For sessions, your code could look like:
// Generate the authentication & Set the Session!!
function gen_auth(){
// Make sure the $PHP_AUTH vars are visible inside the function
global $PHP_AUTH_USER, $PHP_AUTH_PW;
$auth = false; // Assume user is not authenticated
if (isset( $PHP_AUTH_USER ) && isset($PHP_AUTH_PW)) {
// Connect to MySQL
mysql_connect( 'hostname', 'username', 'password' )
or die ( 'Unable to connect to server.' );
// Select database on MySQL server
mysql_select_db( 'your_db' )
or die ( 'Unable to select database.' );
// Formulate the query
$sql = "SELECT * FROM users WHERE
username = '$PHP_AUTH_USER' AND
password = '$PHP_AUTH_PW'";
// Execute the query and put results in $result
$result = mysql_query( $sql )
or die ( 'Unable to execute query.' );
// Get number of rows in $result.
$num = mysql_numrows( $result );
$row = mysql_fetch_array($result);
if ( $num != 0 ) {
session_start();
// A matching row was found - the user is authenticated.
$_SESSION['user']['auth'] = 'Authenticated!';
$_SESSION['user']['user'] = $row['username'];
$_SESSION['user']['expires'] = time()+(60*60*5); // Expires in 5 hours
}
else{
session_start();
$_SESSION['user'] = array();
session_destroy();
}
}
}
function check_auth(){
if(isset($_SESSION['user']['auth']) && $_SESSION['user']['auth'] == 'Authenticated!'){
// They are authenticated, let's make sure their session hasn't expired
if(time() > $_SESSION['user']['expires']){
session_destroy();
return FALSE;
}
else{
return TRUE;
}
}
}
Then, just include this file inside each of your other files, and run either gen_auth() or check_auth().
<?php
/*****************************
** MUST MUST MUST start each of
** your "secured" php pages if
** you use sessions!!
*****************************/
session_start();
/****************************/
include('user_auth.php');
if(check_auth() === FALSE){
// Do the header redirect...
}
~Brett