The gist of it is that you have one file, say "authentication.php", which checks to make sure the user is logged in, and if they aren't, redirects to the login page. Then, in every page which requires authentication, you would include this authentication script.
Here is a (very) simple example:
PHP:
All files requiring authentication
<?php
include "authentication.php";
/* Other content here */
?>
Authentication.php:
<?php
/* Check if user is authenticated */
session_start();
if ($_SESSION["logged-in"]){
/* The user is logged in */
}else{
/* The user is not logged in */
header("location:/login.php");
/* Now kill PHP to prevent further processing */
die();
}
?>
The above is extremely simplified, and is just meant to give you an idea of what needs to be done. More things should, theoretically, be added to make it more secure.
The actual login process is more complicated, but there are tons of tutorials online on how to do this. I'd recommend, however, that you use several security measures, including some of the ones in the following example:
PHP:
/* Storing a password */
function set_password($user_id, $password){
mysql_query("UPDATE USERS SET PASSWORD = '" . mysql_real_escape_string(md5($password))
. "' WHERE USER_ID = " . intval($user_id));
}
function login ($user_name, $password){
$users = mysql_query("SELECT * FROM USERS WHERE " .
"USER_NAME = '" . mysql_real_escape_string($user_name) . "'" .
" AND PASSWORD = '" . mysql_real_escape_string(md5($password))
);
if (mysql_num_rows($users) > 0){
/* Login was a success! */
}else{
/* Invalid login! */
}
}
- The password is encrypted in one-way encryption. See PHP's md5 documentation
- Input strings are escaped using mysql_real_escape_string to prevent SQL injection (for example, an attacker using "' OR TRUE" as a user name causing login to always be successful
- Using intval() to ensure that the value for user_id is a number, and not other text.
Keep these security concerns in mind.