简体   繁体   中英

Redirect user to another page if not logged in?

This may seem pretty confusing at first but I have a log in system on my website. I also have a forum on my website. What I want to do is make it so if people click on the forum button and they aren't logged in, it takes them to the login page, but if they are, it will take them to the forums. I have that in place but I am trying to do one more thing. I also want to make it so if people go in the url and type www.example.com/forums.php, it will check if they are logged in and if they aren't, take them back to the login page and if they are, proceed to take them there. I tried with this but it only works for the first part like I stated, not the rest.

<!-- Main Content -->
        <p class="japanese">プレーンズ</p>
        <p class="dev" contenteditable>currently under development</p>
        <p class="clock"></p>
        <p class="login"><a href="login.php">login</a></p>
        <p class="register"><a href="register.php">register</a></p>
        <?php
            if (isset($_SESSION['u_username'])) {
                echo '<p class="forums"><a href="forums.php">forums</a></p>';
            } else {
                echo '<p class="forums"><a href="login.php">forums</a></p>';
            }
        ?>

On top of your forums.php , check if the session is active, and if not, issue an HTTP redirect.

<?php
if (!isset($_SESSION['u_username'])) {
    header('Location: login.php');
    exit();
}

The exit is important to avoid running any more code on the page if the user is being redirected.

And the redirect should be placed before any output takes place, which means that it should go at the top of the file being executed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM