Logout.php 无效

Logout.php doesn't work

<?php
     session_start();
     if (!isset($_SESSION['korisnik'])) {
      header("Location: index.php");
     } else if(isset($_SESSION['korisnik'])!="") {
      header("Location: home.php");
     }

     if (isset($_GET['Odjava'])) {
      unset($_SESSION['korisnik']);
      session_unset();
      session_destroy();
      header("Location: index.php");
      exit();
     }
     ?>

每次我按注销,home.php只是刷新,会话还没有结束。

您的第一个 if 块首先是 运行,并且会话仍然在那时设置。颠倒你的 if 块的顺序,你可能会得到更好的结果。

<?php

 if (isset($_GET['Odjava'])) {
  unset($_SESSION['korisnik']);
  session_unset();
  session_destroy();
  header("Location: index.php");
  exit();
 }

 session_start();
 if (!isset($_SESSION['korisnik'])) {
  header("Location: index.php");
 } else if(isset($_SESSION['korisnik'])!="") {
  header("Location: home.php");
 }
 ?>

试试这个,因为您需要先检查它是否已设置,否则您的脚本将重定向,因为您的 if 语句位于会话销毁之上

最好使用 PHP documentation 方法:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

为了同时删除会话 cookie。

对我来说这很有效:

setcookie(session_name(), session_id(), 1); 
$_SESSION = [];

即首先使会话过期 (在 1970 年的第一秒之后), 然后清除 $_SESSION 变量。