Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 446
user3026386 Avatar asked Mar 22 '23 03:03

user3026386


2 Answers

You need session_start.

session_start();
if(!isset($_SESSION['username'])) {
    header("Location: log.php");
    exit;
}
like image 81
OneOfOne Avatar answered Apr 06 '23 08:04

OneOfOne


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.

like image 41
farvilain Avatar answered Apr 06 '23 09:04

farvilain