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

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

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成