Page 458 - Beginning PHP 5.3
P. 458
Part III: Using PHP in Practice
Adding More Common Code
Because your members ’ area pages will be in a subfolder inside your book club folder, you need to
modify the displayPageHeader() function inside common.inc.php to change the URL of the
common.css style sheet if called from a page within the members ’ area. Change the first line of
the function definition to:
function displayPageHeader( $pageTitle, $membersArea = false ) {
Now, within the function, change the line that includes the style sheet to:
< link rel=”stylesheet” type=”text/css” href=” < ?php if ( $membersArea )
echo “../” ? > ../common.css” / >
This adds an extra “ ../ ” to the common.css URL if a second argument of true is passed to the
function.
Next, add a function to check that a member is logged in. This will be called from every page in the
members ’ area. If a user who isn ’ t logged in attempts to access a page in the members ’ area, you want to
redirect them to the login page. Add the following checkLogin() function after the existing
setSelected() function in your common.inc.php file:
function checkLogin() {
session_start();
if ( !$_SESSION[“member”] or !$_SESSION[“member”] = Member::getMember
( $_SESSION[“member”]- > getValue( “id” ) ) ) {
$_SESSION[“member”] = “”;
header( “Location: login.php” );
exit;
} else {
$logEntry = new LogEntry( array (
“memberId” = > $_SESSION[“member”]- > getValue( “id” ),
“pageUrl” = > basename( $_SERVER[“PHP_SELF”] )
) );
$logEntry- > record();
}
}
This function makes sure a PHP session is active with session_start() , then checks to see if there ’ s a
Member object stored in the “ member ” element in the $_SESSION superglobal array; this indicates that
a member is logged in, as you see in the next section. If a Member object was found, it is reloaded from
the database by calling Member::getMember() . This not only ensures that the data in the session is
current, but it also makes sure that the currently logged - in member does indeed exist in the members
table (for example, if the member was deleted while they were logged in, then they shouldn ’ t be allowed
to continue using the system).
If the $_SESSION element was not found, or the Member object it contained no longer exists in the
database, the $_SESSION element is cleared (to save having to look the member up again), the user is
redirected to the login page using the PHP header() function, and the application is exited with the
PHP exit command (this prevents any of the protected page content from being sent to the browser). If
the Member object was found, the page view is logged by creating a new LogEntry object, populating it
with the logged - in member ’ s ID and the current page URL, and calling the object ’ s record() method.
420
9/21/09 9:14:09 AM
c14.indd 420 9/21/09 9:14:09 AM
c14.indd 420