PHP中表单验证后的头重定向
我正在尝试将此代码作为表单处理的一部分:PHP中表单验证后的头重定向,php,forms,validation,redirect,header,Php,Forms,Validation,Redirect,Header,我正在尝试将此代码作为表单处理的一部分: <?php if(isset($_POST['senderEmail'])) { try { require '_php/_security/validation.php'; //SEE BELOW $rules = array( 'senderEmail' => 'validEmail', 'emailTe
<?php
if(isset($_POST['senderEmail']))
{
try
{
require '_php/_security/validation.php'; //SEE BELOW
$rules = array(
'senderEmail' => 'validEmail',
'emailTextbox' => 'validTextbox',
);
$validation = new Validation();
if ($validation->validate($_POST, $rules) == TRUE) {
require("_php/database/dbProcessing.php"); //Form Proccessing for database inclusion
}
else {
foreach($validation->emailErrors as $error){
$emailErrors[] = $error;
$_SESSION['$emailErrors'] = $emailErrors;
header('Location:indexmobile.php#emailErrors');
die('ABORT!');
}
}
}
catch (PDOException $e)
{
$error = 'Error adding elements to database: ' . $e->getMessage();
echo "Error: " . $error;
exit();
}
exit();
}
?>
我进行验证的validation.php有以下内容:
<?php
class Validation {
public $errors = array();
public function validate($data, $rules) {
$valid = TRUE;
foreach ($rules as $fieldname => $rule) {
$callbacks = explode('|', $rule);
foreach ($callbacks as $callback) {
$value = isset($data[$fieldname]) ? $data[$fieldname] : NULL;
if ($this->$callback($value, $fieldname) == FALSE) $valid = FALSE;
}
}
return $valid;
}
public function validEmail($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$valid = filter_var($value, FILTER_VALIDATE_EMAIL);
if ($valid == FALSE) $this->emailErrors[] = "The $fieldname needs to be a valid email";
return $valid;
}
}
public function validTextbox($value, $fieldname) {
$valid = !empty($value);
if ($valid == FALSE) {
$this->emailErrors[] = "The $fieldname is required";
return $valid;
} else {
$whitelist = '/^[a-zA-Z0-9 ,\.\+\\n;:!_\-@]+$/';
$textarea = strip_tags($value);
$textarea = mysql_real_escape_string($textarea);
$valid = preg_match($whitelist, $textarea);
if ($valid == FALSE) $this->errors[] = "The $fieldname contains invalid characters";
return $valid;
}
}
}
1-有几种方法可以将消息传递到您要重定向到的页面。一个是通过$\u得到这样的
$message="Some message for the next page.";
$message=urlencode($message);
header("Location:page.php?message=".$message);
然后在page.php上
if(!empty($_GET['message']))
{
$_GET['message'];
}
if (!empty($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
同样,您也可以使用会话(不太安全)
然后在page.php上
if(!empty($_GET['message']))
{
$_GET['message'];
}
if (!empty($_SESSION['message']))
{
echo $_SESSION['message'];
unset($_SESSION['message']);
}
2-我必须查看您传递给validate
函数的内容。你应该做一个var\u dump
的$\u POST
并将其添加到你的问题中
3-这取决于你的标准。如果你只是在检查空虚,那就太过分了。我不知道你需要什么样的文本/认为是有效的,但是正则表达式是一种执行验证的合理方法。
4-见#2。非常感谢您的回复。我很确定你的