user3026386
user3026386

Reputation: 55

PHP, if session is started redirect to a different page

<?php 
1.
 if (isset($_SESSION['username'])) {
header('Location: log.php');
}

2.
 if (session_id() != '') {
    header('Location: log.php');
}
3.
if(isset($_SESSION['username']))
{
    header("Location: log.php");
    exit;
}

4.
 if (session_status() != PHP_SESSION_NONE) {
    header("Location: log.php");
}

?>

I want my php to redirect to from main.php to log.php if the session is live. I want to achieve an effect where logged on users cannot access a page and once they try to do it via a url they get automatically redirected to a different page. Above are the attempts I did and did not work for me.

Upvotes: 4

Views: 19000

Answers (3)

Let&#39;s Yo
Let&#39;s Yo

Reputation: 333

although it's 4 years later,I solve this problem just now.

Please make sure all these matter: 1. All the pages have to set the below parameter in the beginning if (session_status() == PHP_SESSION_NONE) {session_start();}

  1. Adding the session variable must use $_SESSION in order to set the session as globally

  2. exit(); must be added after header("location: $URL ");

Upvotes: 0

farvilain
farvilain

Reputation: 2562

I think that you miss the call to php session_start(). Try this:

<?php
session_start();
if (isset($_SESSION['username'])) { header('Location: log.php'); }
?>

And be sure that your use logged account.

Upvotes: 2

OneOfOne
OneOfOne

Reputation: 99224

You need session_start.

session_start();
if(!isset($_SESSION['username'])) {
    header("Location: log.php");
    exit;
}

Upvotes: 5

Related Questions