无法将HTML表单输入存入PHP Session变量的问题求助
问题分析与修复方案
你的代码存在几处关键错误,导致表单值无法存入Session:
表单提交方法错误
HTML表单仅支持GET和POST两种提交方法,你错误地将表单的method属性设为SESSION,需修改为POST:<form class='white' action = "" method="POST">输入框无效属性
两个<input>标签里的method = "SESSION"是无效属性,直接删除即可:<input type="text" name="email"> <input type="text" name="password">提交逻辑优化
可通过判断提交按钮是否被点击来统一处理表单数据,避免单独判断每个字段:if(isset($_POST["submit"])){ $email = $_POST["email"]; $password = $_POST["password"]; $_SESSION["email"] = $email; $_SESSION["password"] = $password; }HTML结构错误
<body>标签位置错误,需放在<html>标签内的最开始部分,修正后结构如下:<!DOCTYPE html> <html> <body> <?php include('templates/header.php'); ?> <section class='container grey-text'> <!-- 表单内容 --> </section> </body> </html>
修复后的完整代码
<?php session_start(); include('config/dbConnect.php'); if(isset($_POST["submit"])){ $email = $_POST["email"]; $password = $_POST["password"]; $_SESSION["email"] = $email; $_SESSION["password"] = $password; } print_r($_SESSION); ?> <!DOCTYPE html> <html> <body> <?php include('templates/header.php'); ?> <section class='container grey-text'> <h4 class='center'>Please Log In</h4> <form class='white' action = "" method="POST"> <label >Email</label> <input type="text" name="email"> <label >Password</label> <input type="text" name="password"> <div class ="center"> <input type="submit" name="submit" value="Log In" class="btn z-depth-0"> </div> </form> </section> </body> </html>
额外提示
- 确保
session_start()在所有输出(包括HTML、空格)之前调用,否则会触发报错。 - 实际开发中不要在Session中存储明文密码,应对密码进行哈希处理后再验证或存储。
内容的提问来源于stack exchange,提问作者Berkan Özelmacı
相关产品推荐
相关产品推荐

