Make PHP Sites

Last updated: 2015-02-28

Setting restrictions with PHP

In this section, we'll go over how to limit access to pages by the user's logged-in condition.

The code for this version will be written in a procedural method.


Refer to the Get Started section to know what you need to use this tutorial. You must also have an understanding of HTML and how a web page is constructed.


To use this tutorial, we recommend that you use our other lesson, User log-in and log-out, or something similar.


Restricting to logged-in

In our lesson about user-login, a pair of $_SESSION variables are created to recognize a logged-in user: userID and email. To keep them logged in, we must declare session_start() on every page that we want to involve their $_SESSION values.

For example, if you have a profile page or a message inbox page, we'll want to allow only logged-in users to see those pages. So, we need to make sure their $_SESSION variables exist.

In the files you want to include the $_SESSION array, or in files included within them at the very top, use this code:

						if(!isset($_SESSION['userID']) || !isset($_SESSION['email'])){
							header('Location: /login.php');

With the code above, we are verifying whether or not the user has logged in. If either of the $_SESSION variables does not exist, the user must not be logged in. So, we'll use header() to send them to our log-in page. In this example, our log-in page is in the root of our website. It's address would be Make sure you are aiming the Location address correctly.

Use this method any time you want to restict access to logged-in users.

Logging out a user

You may want to provide a way for your users to log out. To do so, we need to get rid of the $_SESSION variables that were allowing them to stay logged in. Create a file called logout.php. This code is all you will need to log a user out:

						$_SESSION['userID'] = NULL;
						$_SESSION['email'] = NULL;
						header('Location: /index.php');

Even though we are trying to log a user out, we must first continue the session with session_start() to make the variable available. Then, we want to change the variables from their normal values to NULL. We'll use the PHP function unset() to get rid of the $_SESSION variables and session_destroy() to eliminate the $_SESSION entirely. Lastly, we'll use header() to redirect the user elsewhere.

Contact us

Questions or problems? Want to contribute to this tutorial or others?

Contact us