douba3378 2010-07-09 07:29
浏览 47
已采纳

PHP会话 - 用户登录后未存储

I am building a basic password protected area on my website and I have a login form.

<!-- login.php -->
<?php
session_start();
?>
<?php if(!empty($_SESSION['user'])) { ?>
<form>
    <input type="text" name="username" />
    <input type = "password" name = "password" />
    <input type="submit" value = "login" />
    <input type="hidden" name="token" value="KdasS2wFgw24F7hh" />
</form>
<?php } else { ?>
You are already logged in.
<? } ?>


<!-- dologin.php -->

<?php
$allowed = //sql checking db
if($allowed > 0) {
    $_SESSION['user'] = $row['user_id'];
}
header("Location: login.php");
?>
  • 写回答

2条回答 默认 最新

  • dongyuanguang3893 2010-07-09 07:30
    关注

    You have missed the session_start() at the top of your dologin.php. It is required at the top of each page before any output has started.

    Without session_start(); you won't have access to create or update a session variable (In your case $_SESSION['user'])

    session_start() : http://php.net/manual/en/function.session-start.php

    Also - Another Helpful Tip:

    I noticed that you haven't got an exit(); after your header(); You will need this so that if the user refreshes the login.php after login the browser won't resubmit the posted data to dologin.php

    Also - Another Helpful Tip:

    You have

    <?php if(!empty($_SESSION['user'])) { ?>
    

    You probably want

    <?php if(empty($_SESSION['user'])) { ?> // No `!`
    

    You will want to show login form if there is no $_SESSION['user']

    So your final code would look like this:

    <!-- login.php -->
    <?php
    session_start();
    ?>
    <?php if(empty($_SESSION['user'])) { ?>
    <form>
        <input type="text" name="username" />
        <input type = "password" name = "password" />
        <input type="submit" value = "login" />
        <input type="hidden" name="token" value="KdasS2wFgw24F7hh" />
    </form>
    <?php } else { ?>
    You are already logged in.
    <? } ?>
    
    
    <!-- dologin.php -->
    
    <?php
    
    session_start();
    
    $allowed = //sql checking db
    if($allowed > 0) {
        $_SESSION['user'] = $row['user_id'];
    }
    header("Location: login.php");
    exit();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义