我有一个注册页面,我要检查javascript和PHP中每个字段的值。问题是我有一个单独的文件后面的注册代码。我把它放在一个单独的文件,因为我正在查询数据库和更多,所以我排除了张贴给自己。然后,我认为重定向到一个单独的错误页面可能是多余的。
所以我想做的是重定向到注册页面,在顶部有错误信息或类似的东西,就像我把表单发布给self一样。我该怎么做呢?
在单独的文件中使用注册码是可以的。
但是,这个文件必须是注册页面本身。
而表单存储在另一个文件中,只是被包含。
这是注册码的草图
<?
include 'config.php';
if ($_SERVER['REQUEST_METHOD']=='POST') {
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
// if no errors - saving data
// and then redirect:
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
和模板包含表单和错误消息
<? if ($err): ?>
<? foreach($err as $e): ?>
<div class="err"><?=$e?></div>
<? endforeach ?>
<? endif ?>
<form>
<input type="text" name="name" value="<?=$form['name']?>">
<textarea name="comments"><?=$form['comments']?></textarea>
<input type="submit">
</form>
这是最常见的表单处理方式,叫做POST/Redirect/GET
你为什么不直接发到self呢?你所要做的就是构造php,这样一旦验证,它就会插入数据…
if( isset($_POST[ 'submit' ]) ){
//Do checks
// if all checks pass do your thing.
// redirect.... header();
exit;
}
// you could then do if( isset($_POST['name']) ){ echo 'name'; } to repopulate the fields so you don't irritate the user.
如果你仍然坚持这样做,仍然使用header()重定向你的用户。(在我看来,这不是一个令人愉快的用户体验……用户必须重新填写所有的数据
你可以发布到你的认证页面,检查他们是否有一个空白字段或其他,然后通过
重定向header(Location:<your url here>?error=1);
返回到原始页面,并让该页检查GET变量$_GET['error']
。如果该变量为1,则显示一些错误。
这是你要找的吗?