【发布时间】:2019-07-12 17:19:05
【问题描述】:
我使用 PHP 创建了一个注册表单。提交表单时,我会检查错误(姓名或电子邮件是否被占用,密码是否正确)。如果出现问题,我会使用header 函数以及信息(错误和字段)将用户返回到表单,然后使用$_GET 方法显示错误并重新填写表单。
有没有办法在不使用header 和$_GET 的情况下在表单上显示错误?我可以从$_POST 收到错误信息并重新填写表格吗?
我不喜欢使用 JavaScript,但如果需要会使用。
我的代码运行良好,只是想知道是否有办法不使用 URL。
我的注册表:
<?php
require 'header.php';
?>
<section>
<?php
if (isset(&_GET['error'])) {
// My error code here...
}
?>
<form action="inc/register.inc.php" method="post">
<input type="text" name="name" placeholder="Name" value="<?php $_GET['name'] ?>" />
<input type="text" name="mail" placeholder="E-mail" value="<?php $_GET['mail'] ?>" />
<input type="password" name="pwd" placeholder="Password" />
<input type="password" name="pwd-repeat" placeholder="Confirm Password" />
<input type="submit" name="registerBtn" value="Registreer" />
</form>
</section>
<?php
require 'footer.php';
?>
处理错误和注册的 php 文件:
<?php
if (isset($_POST['registerBtn'])) {
require 'db_connect.php';
$name = $_POST['name'];
$email = $_POST['mail'];
$pwd = $_POST['pwd'];
$pwd2 = $_POST['pwd-repeat'];
if (empty($name) or empty($email) or empty($pwd) or empty($pwd2)) {
header("Location: ../register.php?error=emptyfields&name=". $name ."&mail=". $email);
exit();
}
else if (!preg_match("/^[\p{L}\p{N}_-]*$/u", $name) and !filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../register.php?error=invalidmailname);
exit();
}
else if (!preg_match("/^[\p{L}\p{N}_-]*$/u", $name)) {
header("Location: ../register.php?error=invalidname&mail=". $email);
exit();
}
else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header("Location: ../register.php?error=invalidmail&name=". $name);
exit();
}
else if ($pwd !== $pwd2) {
header("Location: ../register.php?error=passwordcheck&name=". $name ."&mail=". $email);
exit();
}
else {
// More code here... but you get the gist.
}
}
else {
header("Location: ../register.php");
exit();
}
【问题讨论】:
-
请分享一些代码,以便我们了解您是如何解决问题的
-
您可以使用会话来临时存储信息。
-
添加了我的代码,忘记了
-
if (empty($name) or empty($email) or empty($pwd) or empty($pwd2)) { // echo 'please fill the form'; }....