PHP redirect if not logged in [closed]

2020-03-06 03:51发布

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.

标签: php redirect
4条回答
来,给爷笑一个
2楼-- · 2020-03-06 03:55

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.

查看更多
够拽才男人
3楼-- · 2020-03-06 04:08

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.

查看更多
放荡不羁爱自由
4楼-- · 2020-03-06 04:11

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.

查看更多
乱世女痞
5楼-- · 2020-03-06 04:13
<?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";
查看更多
登录 后发表回答