Creating A Log In System - Part 3

So, we've created our log in system and everything seems to work. How do we enforce that certain pages are only accessible to users that are logged in? Easy. Just add four lines of code:

// if we're not logged in, send the user to login.php
if ( isset($_SESSION["loggedIn"]) == false || $_SESSION["loggedIn"] == false ) {
	header("Location: login.php");
	exit;
}

Where does this code go in our files? It goes into each controller, underneath all the require_once statements and before you start handling any GET or POST requests.

Let's add it to our index.php file.

...
require_once "indexviews.php";
use \IndexViews\IndexViews;

// if we're not logged in, send the user to login.php
if ( isset($_SESSION["loggedIn"]) == false || $_SESSION["loggedIn"] == false ) {
	header("Location: login.php");
	exit;
}

// handle GETS
if ( isset($_GET["do"]) == true ) {
...

Now, when a user that is not logged in tries to show up to index.php, they will be redirected to login.php.

Just for fun, let's see what's in our $_SESSION:

This code should be put into index.php in your webroot directory. This code should go right above // if we're not logged in, send the user to login.php

echo '<pre>';
print_r($_SESSION);
echo '</pre>';

After trying to log in, you should see something like this in your browser:

Array
(
    [do] => login
    [csrf] => 92c5fbfe7e09728a
    [username] => asdf
    [password] => asdfasdfasdf
)

Which brings us to our next serious talk about security. We're sending our password in the clear to the server. This is bad. But, it's not bad if we secure our website using a https certificate.

What is a https certificate? It's basically a set of files that form a certificate that you install onto your server which when set up correctly, allows the browser to form a secure encrypted tunnel to the server. This makes it so that we can pass our credentials to the server, because the browser will encrypt them before it gets sent to the server. The server will then decrypt them and pass them to PHP for us to process. Basically, this is all transparent to the user and the programmer creating the site, making it an easy task to accomplish.

How do you get https certificates? Unfortunately, this is out of the scope of this lesson. But, if you are using a reputable service, they should offer free Let's Encrypt certs. You can also pay for certs from reputable companies and then install those certs on your server. I'm thinking about adding this to my System Administration lesson plan in the future...

Just know that it needs to be done, otherwise, there really is no point in adding a log in system. Anyone on the wire can sniff your packets and steal your credentials.