douniwan_0025 2016-03-28 08:25
浏览 35
已采纳

表单文本以指定会话名称

I want to allow the user to input some text, then use that text as their session username and then echo a welcome "username" at the top of each page, and then a logout button which will end the session and allow for the user to input a new username

Currently the code will allow the user to input a name, and then a Welcome will appear for that name, but it will be destroyed if the user changes pages, and the textfield to input a name never disappears either - This is the master page in codeigniter

<form action="" method="POST">
<input type="text" name="input_value">
<input type="submit" name ='in'  value="LogIn">
</form>

<?php
    if (session_status() == PHP_SESSION_NONE) {
      session_start();
        $_SESSION['userses'] = '';
    }

   if(session_status() == PHP_SESSION_ACTIVE && $_SESSION['userses']=='' ){

  $_SESSION['userses'] = $_POST['input_value'];
  echo "Welcome, ".$_SESSION['userses']."!";
   }

 else{
 echo "Welcome, ".$_SESSION['userses']."!";
  }



?>
<form action="<?php session_destroy(); ?>" method="POST">
<input type="submit" name='out' value="LogOff">
</form>
  • 写回答

1条回答 默认 最新

  • doufei6456 2016-03-28 08:30
    关注

    You have to change

    if(session_status() == PHP_SESSION_ACTIVE && $_SESSION['userses']=='' )
    

    to

    if(isset($_POST['in']) ){
    
     $_SESSION['userses'] = $_POST['input_value'];
    }
    

    so when he submits username, this if will catch the post request and then add input to your username

    you don't need to check session_status

    edit:

    and as the comments said, put session_start(); at the beginning of every page

    example of code :

    <?php session_start();
    if(isset($_SESSION['userses'])) echo "Welcome".$_SESSION['userses']; 
    ?>
    <form action="" method="POST">
    <input type="text" name="input_value">
    <input type="submit" name ='in'  value="LogIn">
    </form>
    
    <?php
    
    if(isset($_POST['in']) ){
    
     $_SESSION['userses'] = $_POST['input_value'];
    }
    ?>
    <form action="<?php session_destroy(); ?>" method="POST">
    <input type="submit" name='out' value="LogOff">
    </form>
    

    You are using codeigniter, why not use session library :

    https://www.codeigniter.com/user_guide/libraries/sessions.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 vmware exsi重置后的密码
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面