我应该何时在PHP中启动和销毁会话


When should I start and destroy session in PHP

我正在制作一个简单的oauth站点。

index.php:中

<?php
session_start();
if (empty($_SESSION['authentication']))
    $_SESSION['authentication'] = 'pending';
?>
<html>
<form action="oauth.php" method="post">
    <span>
    <?php
        echo $_SESSION['authentication'];
    ?>
    </span>
    <input type="hidden" name="action" value="authenticate">
    <input type="submit" value="authenticate">
</form>
</html>

oauth.php:中

<?php
session_start();
if (isset($_POST['action']) and $_POST['action'] == 'authenticate') {
    $url = $serverAuth ... ;
    header('Location: ' . $url); //google oauth, it will come back to oauth.php
    exit();
}
if (isset($_GET['code'])) {
    $ch = curl_init($serverToken);
    $result = curl_exec($ch);
    $tokens = json_decode($result, true);
    if (isset($tokens['access_token'])) {
        $_SESSION['authentication'] = 'good';
        $_SESSION['access_token'] = $tokens['access_token'];
    } else {
        $_SESSION['authentication'] = 'error';
    }
    header('Location: ./');
    exit();
}
if (isset($_GET['error'])) {
    if ($_GET['error'] == 'access_denied')
        $_SESSION['authentication'] = 'denied';
    else
        $_SESSION['authentication'] = 'error';
    header('Location: ./');
    exit();    
}
?>

我想让网站像:默认情况下,$_SESSION['authentication']是"挂起"的;当我刷新页面时,每个会话变量都消失了,$_SESSION['authentication']重置为默认值。但我无法在index.php的开头重置$_SESSION,因为oauth.php中的函数有header()可以重定向到此页面。

如何处理?

您必须在需要访问$_SESSION的每个页面上启动会话。只有在明确要求时才销毁它,例如注销时。