7

I have been trying to make this following functionality work on my website, however I'm kinda struggling with it. Perhaps one of you can help me out?

I am developing a website which must be inaccessible (except the login of course) unless you are logged in. I was trying to make an automatic redirect to the login page if the user isn't logged in. I'm using HTML, CSS, and PHP at the moment.

If my remaining source is needed please tell me, I'll temporarily host the site online.

YetAnotherRandomUser
  • 1,320
  • 3
  • 13
  • 31
J.I.N Kleiss
  • 187
  • 1
  • 2
  • 12

4 Answers4

17

If you're not using any frameworks, try simply:

if(!isset($_SESSION['login'])){ //if login in session is not set
    header("Location: http://www.example.com/login.php");
}

The session parameter and the redirect location depends on the architecture that you're using on your web project.

Dropout
  • 13,653
  • 10
  • 56
  • 109
  • The redirect is working, however it also works when I am logged in I tried to change ['login'] but I can't figure out what it should be changed to. Can you see in the source I provided earlier what ['login'] should be changed to? (I didn't write the login script myself and I can't figure out where he saves this session in.) Also I have changed the location URL – J.I.N Kleiss May 24 '13 at 14:52
  • sure, can you provide me a link to the source? thanks – Dropout May 24 '13 at 14:55
3
<?php
header("Location: http://www.example.com/"); /* Redirect browser */

/* Make sure that code below does not get executed when we redirect. */
exit;
?>

or in javascript

// similar behavior as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";
Igor S.
  • 3,332
  • 1
  • 25
  • 33
0

When you determine that they are not logged in you can issue a redirection header:

header("Location: http://www.example.com/log-in/");

This is described in detail in the PHP Manual: Header.

Fenton
  • 241,084
  • 71
  • 387
  • 401
0

The login script you are using is already checking if the user id logged in in the index.php:

if ($login->isUserLoggedIn() == true) {
    // the user is logged in. you can do whatever you want here.
    // for demonstration purposes, we simply show the "you are logged in" view.
    include("views/logged_in.php");

} else {
    // the user is not logged in. you can do whatever you want here.
    // for demonstration purposes, we simply show the "you are not logged in" view.
    include("views/not_logged_in.php"); // Change this part to your needs.
}

You can change this include("views/not_logged_in.php"); to whatever page you want.

MISJHA
  • 998
  • 4
  • 12