Members Area
Members Area is pages in an application that are only available for logged in users.
On Day 18, we created login page (login.php). If login was successful, we just show a message.
PHP Code:
echo "Password Matched";
Instead of showing the message, we need user redirected to another page.
Redirect User To Another Page
In PHP, you can redirect a user to another page using code
PHP Code:
header("Location: URL_HERE");
Lets Test
hostonnet.php
PHP Code:
<?php
header("Location: http://hostonnet.com");
Upload the file to your web site. On visiting the file, you will get redirected to URL specified in the code, in our case http://hostonnet.com
Create Members Only Page
Now we know how to redirect user to another page/URL.
Lets create our Members only page, so we can redirect users to this page after successful login.
tasks.php
PHP Code:
<?php
echo "<h1>Welcome to members only page. This page is under construction.</h1>";
Since our application is TODO task manager, we named our members page tasks.php
Edit login.php and redirect user to tasks.php
Open login.php
Find
PHP Code:
if ($userInfo['password'] == $password) {
echo "Password Matched";
}
Replace with
PHP Code:
if ($userInfo['password'] == $password) {
header("Location: tasks.php");
exit;
}
Check if User Logged In
Currently our tasks.php is simple PHP page. It do nothing other than printing some text.
What we need to do is make sure only logged in members can see this page.
How we know if user is logged in ? We can set a COOKIE or SESSION.
When user login, we set a SESSION variable. On tasks.php page, we check if SESSION is set, if not redirect user to login page.
So lets edit login.php again
login.php
Find
PHP Code:
if ($userInfo['password'] == $password) {
header("Location: tasks.php");
exit;
}
Replace With
PHP Code:
if ($userInfo['password'] == $password) {
session_start();
$_SESSION['AUTH_USER'] = $userInfo;
header("Location: tasks.php");
exit;
}
tasks.php
Use following code for tasks.php
PHP Code:
<?php
session_start();
if (!isset($_SESSION['AUTH_USER'])) {
echo "User is not logged in<br>";
echo "<a href=login.html>click here</a> to go to login page";
exit;
}
echo "<h1>Welcome to members only page. This page is under construction.</h1>";
We check if SESSION is set. If no session set, we show error message and exit program.
Logging Off User
Logging off user is simple. Just destroy the session.
logout.php
PHP Code:
<?php
session_start();
session_destroy();
echo "<p>User logged off successfully.</p>";
Now lets add a log out link from our tasks page.
Open tasks.php
Add
PHP Code:
echo "<p><a href='logout.php'>Click here to logout</a>";
to end of the file.
Bookmarks