我的表单快把我逼疯了,它应该设置为如果字段为空就停止发送,但它总是通过。如果没有或全部填写,它将始终显示我的"谢谢,您的消息已成功发送"消息。
这是我的表单:
<?php
//////////////////////////
//Specify default values//
//////////////////////////
//Your E-mail
$your_email = 'myemail';
//Default Subject if 'subject' field not specified
$default_subject = 'From My Contact Form';
//Message if 'name' field not specified
$name_not_specified = 'Please type a valid name';
//Message if 'message' field not specified
$message_not_specified = 'Please type a vaild message';
//Message if e-mail sent successfully
$email_was_sent = 'Thanks, your message successfully sent';
//Message if e-mail not sent (server not configured)
$server_not_configured = 'Sorry, mail server not configured';
///////////////////////////
//Contact Form Processing//
///////////////////////////
$errors = array();
if(isset($_POST['message']) and isset($_POST['name'])) {
if(!empty($_POST['name']))
$sender_name = stripslashes(strip_tags(trim($_POST['name'])));
if(!empty($_POST['message']))
$message = stripslashes(strip_tags(trim($_POST['message'])));
if(!empty($_POST['email']))
$sender_email = stripslashes(strip_tags(trim($_POST['email'])));
if(!empty($_POST['subject']))
$subject = stripslashes(strip_tags(trim($_POST['subject'])));
//Message if no sender name was specified
if(empty($sender_name)) {
$errors[] = $name_not_specified;
}
//Message if no message was specified
if(empty($message)) {
$errors[] = $message_not_specified;
}
$from = (!empty($sender_email)) ? 'From: '.$sender_email : '';
$subject = (!empty($subject)) ? $subject : $default_subject;
$message = (!empty($message)) ? wordwrap($message, 70) : '';
//sending message if no errors
if(empty($errors)) {
if (mail($your_email, $subject, $message, $from)) {
echo $email_was_sent;
} else {
$errors[] = $server_not_configured;
echo implode('<br>', $errors );
}
} else {
echo implode('<br>', $errors );
}
}
?>
CLIENT SIDE METHOD将required
属性添加到您希望在提交表单之前填充的字段的每个元素中!
服务器端方法
如果您不想在服务器端执行此操作,请检查字段是否为空,否则将重定向回:
if(!(isset($_POST['message']) and isset($_POST['name'])))
header('locaition: formurl');
最推荐:任何客户端验证都必须在服务器端重复
重要,但稍微跑题
虽然这并没有真正回答你的问题,但我强烈建议你看看邮件注入。每当您决定使用客户端数据发送邮件消息时,都有风险。你似乎没有对数据进行足够的清理。
我在几个场合检查过做类似事情的代码(用PHP发送邮件,或者处理联系表单)。关于这一点,尤其是关于邮件注入的话题,我要说的可以在这里和这里找到。两个代码审查都包含了值得一读的链接。
无论如何,回答你的问题:
如果你不希望PHP在出错时到达某个语句(如:mail()
),使用允许你控制流程的代码(在到达语句之前停止执行)。
最简单、最容易的方法是使用一个函数:
/**
* Sends mail using data in $data argument
* requires $fields to be an assoc array where
* keys == field names, and values = null|| default value
* null for required fields, default value for optional fields
* If $data is invalid, an InvalidArgumentException is thrown
* @param array $data
* @param array $fields
* @return bool mail() return value
* @throws InvalidArgumentException
*/
function sendMail(array $data, array $fields)
{
foreach ($fields as $field => $val)
{
if (isset($data[$field]))
{//data is set
if ($field === 'email')
{//sanitize
$val = filter_var($data[$field], FILTER_SANITIZE_EMAIL);
if (!filter_var($val, FILTER_VALIDATE_EMAIL))
{//if email is not valid, throw exception
throw new InvalidArgumentException(
sprintf(
'invalid %s value: %s',
$field,
$data[$field]
)
);
}
}
else
{//basic, crude sanitation, not enough to protect agains mail injection
$data[$field] = nl2br(strip_tags(trim($data[$field])));
}
}
else
{
if (!$val)
throw new InvalidArgumentException(
sprintf(
'%s is a required field',
$field
)
);
$data[$field] = $val;
}
}
return mail('your_email', $data['subject'], wordwrap($data['message'],70), 'From: '.$data['email']);
}
请注意,我为电子邮件地址添加了特殊的卫生/验证检查。一个值得记住的函数是filter_var
。它有特殊的常量来验证和/或清理值。在这里查看可用的过滤器。
现在这段代码可能看起来很冗长(确实如此)。如果您愿意,您可以很容易地用一个简单的return 'The error message string';
语句替换所有的throw new InvalidArgumentException
语句。这将改变你使用这个函数的方式。对于抛出的异常,可以这样使用函数:
if ($_POST)
{//if there is post data
try
{//try - catch block
//which fields are required, which have default values, defined here
$validate = array(
'email' => null,//required
'message' => null,//required
'name' => 'No Name',//default val,
'subject' => 'Default subject'//default
);
//call function, check what it returns
if (sendMail($_POST, $validate))
echo 'Message was sent';//echos if return value was true
else//if false:
echo 'failed to send message';
}
catch(InvalidArgumentException $e)
{//if an exception was thrown
echo 'Error: ', $e->getMessage();//echo the error message
}
}
现在,假设我们已经用一个简单的return 'error-string';
语句替换了所有的throw
语句。现在的用法如下:
if ($_POST)
{
$validate = array();//same array as above
$return = sendMail($_POST, $validate);
if ($return === true)//use type and value check: ===, not ==
echo 'Message sent';
elseif ($return === false)
echo 'Failed to send message';
else
echo 'Error: ', $return;//$return is a string: error message returned by function
}
那将是我的解决你的问题的方法
这个问题很简单,如果其中一个是空的,您不需要告诉脚本停止。
将以下内容添加到脚本中:
if($errors) {
foreach($errors as $value) {
echo $value . "<br/>";
}
exit();
}
这将在发送错误后停止脚本。
解决方案是:
(...)
///////////////////////////
//Contact Form Processing//
///////////////////////////
$errors = array();
if(!empty($_POST['message']) and !empty($_POST['name'])) {
(...)
如果仍然错误,请确保字段确实为空。
(...)
///////////////////////////
//Contact Form Processing//
///////////////////////////
$errors = array();
if(!empty($_POST['message']) and trim($_POST['message']) and !empty($_POST['name']) and trim($_POST['name'])) {
(...)