【发布时间】:2017-06-30 20:35:30
【问题描述】:
我对 html 和 php 非常陌生,需要一点帮助。这实际上是我在 stackoverflow 上的第一篇文章,所以如果内容做得不对,我深表歉意。
我要求用户提供用户名和密码,然后我想获取该信息并在通过 PHP 在服务器上运行的脚本中使用它。
我遇到的问题是用户第一次访问 html 并填写表单时,php 文件中的 $_POST 没有收到任何内容。我知道这是因为我在 php 文件中回显了变量。但是在用户按下php页面上的“返回”按钮并返回到html后,再次浏览时,一切正常。
所以代码可以工作,只是第一次不能工作。有什么想法吗?
HTML:
<body>
<div class="loader" id="container" style="visibility:hidden;"></div>
<form method="post" action="Login_Page.php">
<b>Username:</b><input type="text" placeholder="University ID" name="userid" autofocus/>
<b>Password:</b><input type="password" placeholder="Password" name="pswrd"/>
<input type="submit" class="button" value="Submit" onclick="showDiv()"/>
</form>
</div>
</body>
CSS:
.loader {
position: fixed;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 9999;
background: url('https://cdn.shopify.com/s/files/1/1247/2733/t/4/assets/loading.gif?11916921113420493983') 50% 50% no-repeat rgba(255, 255, 255, 0.3);
filter: alpha(opacity=60);
}
脚本:
<script type="text/javascript">
showDiv = function() {
document.getElementById("container").style.visibility="visible";
}
</script>
PHP:
<?php
$username = $_POST["userid"];
$pswrd = $_POST["pswrd"];
echo $username;
echo $pswrd;
$cmd = "path/to/script.sh $username $pswrd";
exec($cmd, $output, $return);
if ($return != "0") {
echo '<h1><b>Login was unsuccessful. Please try again.</b></h1>';
echo '<form>';
echo '<input type="button" value="Back" onClick="history.go(-1);return true;"/>';
echo '</form>';
} else {
echo '<h1><b>Login was Successful.</b></h1>';
}
?>
【问题讨论】:
-
试着在你的 Login_Page.php 文件中加入这个:
-
首先,在 Login_Page.php 中检查请求是否为 post 请求。
if ($_SERVER["REQUEST_METHOD"] === "POST")否则重定向到用户输入凭据的页面。 -
所以我第一次浏览表单时,数组是空的。但是在我按下“返回”按钮并再次执行此操作后,数组就有了用户名和密码。感谢您的评论@Difster
-
您在浏览器控制台中看到任何错误吗?如果 $_POST 数组为空,则意味着数据根本没有到达那里。看看 javascript 用它做了什么。
-
@Ibu,添加您的建议后,我重定向回 html。我第一次浏览表单时,它会立即重定向回 html,但我第二次浏览表单时,一切正常。