Verify Authentication3:52 with Alena Holligan
In functions_auth.php we'll create a new function named isAuthenticated. This function will need to read our session to know if a user is logged in.
<?php if (isAuthenticated()) : ?> <li><a href="/add.php">Add Book</a></li> <?php endif; ?>
<?php if (isAuthenticated()) : ?> <li><a href="/procedures/doLogout.php">Logout</a></li> <?php else: ?> <li><a href="/login.php">Login</a></li> <li><a href="/register.php">Register</a></li> <?php endif; ?>
In our inc folder, we're going to add 0:00 a New File named functions_auth.php. 0:05 We'll also need to add this file to our bootstrap file. 0:11 Duplicate that line and we'll change it to auth and then we can close it. 0:17 In our functions_auth file, 0:23 we're ready to create a new function. 0:27 We'll name this isAuthenticated. 0:31 This function will need to read our session to know if a user is logged in, 0:40 for the session variable to work inside of this function, 0:45 we'll need a way to access it. 0:49 One simple approach is to call the global $session; For 0:51 more options see the notes associated with this video. 0:56 We can then use session->get and look for 1:02 our' auth_logged_in' variable. 1:08 The value of this variable should be true if the user is logged in. 1:14 The get method allows us to specify a default value as the second parameter. 1:20 So we'll use for our second parameter, false, 1:26 then we can simply return those results. 1:31 Either true, if the user is logged in, or false if the user is not logged in. 1:37 Now, let's use that isAuthenticated function in our navigation to show 1:44 the proper length. 1:49 Under templates, We have a nav.php. 1:52 We only want to add books if the user is authenticated. 1:58 So we can add a conditional around that item. 2:03 If isAuthenticated. 2:11 And then 2:20 endif;. 2:25 Next, if the user is logged in, we don't need to show the login and register links. 2:30 Instead, we want to show log out. 2:37 So let's add another conditional. 2:41 If, isAuthenticated. 2:42 We're going to add a new item. 2:56 So let's copy the Login. 2:58 And then we can add an else. 3:00 And finally, endif;. 3:09 We'll change the login to Logout. 3:18 And we'll link directly to procedures doLogout. 3:23 Let's go back and refresh our browser to see the changes in our navigation. 3:31 We can see the add book link which hasn't changed. 3:37 But now instead of login and register we see Logout. 3:41 But before that Logout will work we need to add that procedure. 3:46
You need to sign up for Treehouse in order to download course files.Sign up