简体   繁体   English

PHP,如果会话开始重定向到不同的页面

[英]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. 如果会话是活动的,我希望我的php重定向到main.php到log.php。 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. 我希望实现登录用户无法访问页面的效果,一旦他们尝试通过URL进行操作,他们就会自动重定向到不同的页面。 Above are the attempts I did and did not work for me. 以上是我所做的尝试,并没有为我工作。

You need session_start . 你需要session_start

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

I think that you miss the call to php session_start(). 我想你错过了对php session_start()的调用。 Try this: 尝试这个:

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

And be sure that your use logged account. 并确保您使用记录帐户。

although it's 4 years later,I solve this problem just now. 虽然它已经过了4年,但我刚刚解决了这个问题。

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。所有页面必须在开头设置以下参数if(session_status()== PHP_SESSION_NONE){session_start();}

  1. Adding the session variable must use $_SESSION in order to set the session as globally 添加会话变量必须使用$ _SESSION才能将会话设置为全局

  2. exit(); 出口(); must be added after header("location: $URL "); 必须在标题后添加(“location:$ URL”);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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