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

重要ですが、少しトピックから外れています

これはあなたの質問への回答にはなりませんが、Mail-injection について調べることを強くお勧めします。client-data を使用してメール メッセージを送信することを決定するときはいつでも、危険にさらされます。データを十分にサニタイズしていないようです。
私は、似たようなこと (PHP でメールを送信したり、連絡先フォームを処理したり) を行ったコードを 2 回見直しました。それについて、特にメールインジェクションについて私が言わなければならなかったことは、ここここにあります。どちらのコード レビューにも、読む価値のあるリンクが含まれています。


とにかく、あなたの質問に答えるには:

問題が発生したときに 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. 値を検証および/またはサニタイズするための特別な定数があります。ここで利用可能なフィルタを確認してください

このコードは非常に冗長に見えるかもしれません (そして実際にそうです)。throw new InvalidArgumentException必要に応じて、すべてのステートメントを単純なステートメントに簡単に置き換えることができますreturn 'The error message string';。これにより、この機能の使用方法が変わります。
例外がスローされると、次のように関数を使用します。

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

ここで、すべてのthrowステートメントを単純なreturn 'error-string';ステートメントに置き換えたとします。使用法は次のようになります。

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
}

それがあなたの問題に取り組む私の方法です

于 2014-07-17T12:00:22.113 に答える
1

クライアント側の方法requiredフォームが送信される前に入力されたくないフィールドの各要素に属性を追加してください!

サーバー側の方法

サーバー側で実行したくない場合は、フィールドが空でないかどうかを確認し、そうでない場合はリダイレクトして戻します。

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 に答える