0

我的表格让我发疯,如果字段为空,它应该全部设置为停止发送,但它总是通过。如果没有填写或全部填写,它将始终显示我的“谢谢,您的消息已成功发送”消息。

这是我的表格:

<?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 );
    }
}
?>
4

4 回答 4

1

Imporant, but slightly off-topic

Though this does not really answer your question, I do urge you to look into Mail-injection. Whenever you decide to send a mail message using client-data, you are at risk. You don't seem to be sanitizing the data enough.
I have reviewed code on a couple of occasions that did similar things (sending mails with PHP, or processing contact forms). What I had to say about that, especially on the subject of mail-injection can be found here, and here. Both code-reviews contain links that might also be worth reading.


Anyway, to answer your question:

If you don't want PHP to reach a certain statement (ie: mail()) in when something goes wrong, use code that allows you to control the flow (stop execution before the statement is reached).
The simplest, and easiest way to do this is through use of a function:

/**
 * 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']);
}

Note that I added special sanitation/validation checks for email addresses. A function worth remembering is filter_var. It has special constants to validate and/or sanitize values. See which filters are available here.

Now this code may seem quite verbose (and it is). If you want, you could easily replace all the throw new InvalidArgumentException statements with a simple return 'The error message string'; statement. This will change the way you use this function.
With the exceptions being thrown, you use the function like so:

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
    }
}

Now, assume we've replaced all the throw statements with a simple return 'error-string'; statement. Now the usage looks like this:

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
}

That would be my way to tackle your problem

于 2014-07-17T12:00:22.113 回答
1

CLIENT SIDE METHODrequired在提交表单之前为您不想填写的字段的每个元素添加属性!

服务器端方法

如果您不想在服务器端执行此操作,请检查该字段是否为空,否则重定向回来:

if(!(isset($_POST['message']) and isset($_POST['name'])))
    header('locaition: formurl');

最推荐:任何客户端验证必须在服务器端重复

于 2014-07-17T11:32:19.897 回答
0

解决方案是:

(...)
///////////////////////////
//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'])) {
(...)
于 2014-07-17T11:36:15.883 回答
0

问题相当简单,如果其中一个为空,您不会告诉您的脚本停止。

如下添加到您的脚本中:

if($errors) {
    foreach($errors as $value) {
         echo $value . "<br/>";
    }
    exit();
}

这将在发送错误后停止您的脚本。

于 2014-07-17T11:30:54.800 回答