我的网站页脚中有一个表格,该表格显示在每个页面上。我需要这样做,如果用户使用空白字段提交表单,它将在表单中标记错误消息。当前,它将它们定向到另一个页面,在那里数据被提交到另一台服务器。我已经为此使用JavaScript,但是需要使用服务器端代码添加一个附加的验证层。
我知道如何检测表单字段是否为空,但是如何使用服务器端代码重定向回引用页面并包含一些可在页脚中使用的参数来检测哪些字段为空?
我假设我必须将PHP的header()与http_referer一起使用,但是如何将参数传递回该页面而不在URL中显示任何内容?
最佳答案
在$_SESSION
中保留无效/空字段的记录,并在表单中用CSS标记它们:
session_start();
// When you begin validating your form, clear out any old fields from $_SESSION
$_SESSION['previous'] = array();
$_SESSION['invalid'] = array();
// when you encounter an empty or invalid field,
// add it to an array in $_SESSION
$_SESSION['invalid']['fieldname'] = TRUE;
// Store the previous POST value too
$_SESSION['previous']['fieldname'] = $_POST['fieldname'];
在您的表单中,您可以检查是否存在无效字段,并添加CSS类以表明无效。这将设置类
invalid
:<input name='fieldname' type='text'
class='<?php if (isset($_SESSION['invalid']['fieldname'])) echo "invalid";?>'
value='<?php if (isset($_SESSION['previous']['fieldname'])) echo htmlentities($_SESSION['previous']['fieldname'], ENT_QUOTES); ?>'
/>
对所有表单字段执行此操作。使用相同的方法保留以前的
$_POST
值,并将它们回显到字段的value
属性中。
关于php - 重定向回提交表单的页面时,如何在PHP中标记缺少的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6838732/