【问题标题】:validate php contact form with checkbox使用复选框验证 php 联系表单
【发布时间】:2018-10-26 14:44:05
【问题描述】:

我正在尝试向联系表单添加另一个验证。我需要用户在提交表单之前检查表单底部的复选框。

这是我到目前为止所拥有的,它验证了表单。我想知道如何添加一个复选框,以便仅在选中该框时才提交表单

		<section class="form wow fadeInRight" data-wow-duration="2s">
            <div class="container">
              <div class="row">
                <div class="col-md-6 col-md-offset-3 contact-form">
	               <h2>Contact Us</h2>
				   <p>Please do not hesitate to get in touch with us by filling out the form or using the contact details below</p>
                  <form class="form-horizontal" action="" id="form" method="post" name="form">
                    <input type="hidden" name="bts" value="" />
                    <input type="hidden" name="page" value="<?php echo $current_url; ?>" />
                    <div class="form-group">
                      <div class="col-md-12">
                        <input type="text" class="form-control" id="name" name="name" placeholder="Your Name:*" value="<?php echo $send_data['name']; ?>" required>
                      </div>
                    </div>
                    <div class="form-group">
                      <div class="col-md-12">
                        <input type="email" class="form-control" id="email" name="email" placeholder="Email Address:*" value="<?php echo $send_data['email']; ?>" required>
                      </div>
                    </div>
                    <div class="form-group">
                      <div class="col-md-12">
                        <input type="tel" minlength="10" class="form-control" id="tel" name="tel" placeholder="Contact Number:*" value="<?php echo $send_data['tel']; ?>" required>
                      </div>
                    </div>
                    <div class="form-group">
                      <div class="col-md-12">
                        <textarea class="form-control" id="message" name="message" placeholder="General Enquiry:" required><?php echo $send_data['message']; ?></textarea>
                      </div>
                    </div>
                    <div class="form-group">
                      <div class=" col-md-12">
                        <button type="submit" class="button btn btn-warning">Send</button>
                      </div>
                    </div>
                  </form>
                </div>
              </div>
            </div>
          </section>

<?php

	$target_page = false;

	$send_to = config('company_email');
	$company_name = config('company_name');

	$errors  = array();
	$posted  = false;
	$success = false;

	$current_url = (isset($_POST['page']) && !empty($_POST['page'])) ? $_POST['page'] : 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

	# is this the normal or quick form?
	$quick = (isset($_POST['type']) && $_POST['type'] == 'quick') ? true : false;

	# set up the common fields
	$send_data = array();
	$send_data['name']    = (isset($_POST['name']) && !empty($_POST['name'])) ? $_POST['name'] : '';
	$send_data['email']   = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : '';

	# if this is not the quick form then add the additional fields
	if (!$quick) {
		$send_data['tel'] = (isset($_POST['tel']) && !empty($_POST['tel'])) ? $_POST['tel'] : '';
	}

	$send_data['message'] = (isset($_POST['message']) && !empty($_POST['message']) && $_POST['message'] != ' ') ? $_POST['message'] : '';

	# check if the form has been submitted
	if (isset($_POST['bts']) && $_POST['bts'] == '') {

		# the form has been posted
		$posted = true;

		# check the name value
		if ($send_data['name'] == '') {
			$errors[] = 'Please fill in your name';
		}

		# check the email value
		if ($send_data['email'] == '') {
			$errors[] = 'Please fill in your email address';
		} else {
			# validate the email
			$validate_email = filter_var($send_data['email'], FILTER_VALIDATE_EMAIL);
			if (!$validate_email) {
				$errors[] = 'Please check your email address is correct';
			} else {
				# check the domains MX records
				if(!checkdnsrr(array_pop(explode("@",$send_data['email'])),"MX")){
					$errors[] = 'Please use a valid email address';
				}
			}
		}

		# if this is not the quick form then check the additional fields
		if (!$quick) {
			if (strlen($send_data['tel']) < 10) {
				$errors[] = 'Please add a valid telephone number!';
			}
		}

		# check the message
		if ($send_data['message'] == '') {
			$errors[] = 'Please fill in a message';
		}

		# if there are no errors then send the message
		if (count($errors) == 0) {

			$send_from = $send_data['name']  . "<" . $send_data['email']  . ">";

			$subject = 'Enquiry From Website ' . $_SERVER['HTTP_HOST'];

			$email_message = 'Below are the details that have been submitted on your contact form' . "\n\n";

			$email_message .= '________________________________________' . "\n\n";

			if (count($send_data) > 0) {
				foreach ($send_data as $key => $value) {
					$email_message .= $key . ' : ' . htmlspecialchars($value) . "\n";
				}
			}

			$email_message .= '________________________________________' . "\n\n";

			$email_message .= 'IP : ' . $_SERVER["REMOTE_ADDR"] . "\n\n";
			$email_message .= 'URL : ' . $current_url . "\n\n";
			$email_message .= 'WUKmedia | http://wukmedia.uk';

			#$headers = "From: " . strip_tags($send_from) . "\r\n";
			#$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
			#$headers .= "MIME-Version: 1.0\r\n";
			#$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

			if (mail($send_to, $subject, $email_message, "From: " . $send_from)) {
				$success = true;

				# now that the enquiry has been sent we can confirm to user
				$FromCompany    =  $company_name . "<" . $send_to . ">";
				$thanks_email   =  "Thank you for your enquiry " . $send_data['name'] . ".\n";
				$thanks_email   .=  "We will be back in touch with you shortly, \n\n";
				$thanks_email   .=  $company_name . "\n";
				$thanks_email   .=  'http://' . $_SERVER['HTTP_HOST'] . "\n\n\n";

				mail($send_data['email'], "Thanks for the Enquiry", $thanks_email, "From: " . $send_from);

				# now store the data in a json array
				$send_data['ip'] = $_SERVER["REMOTE_ADDR"];
				$send_data['timestamp'] = time();

				$json_array = "\n" . json_encode($send_data);

				$json_file = $_SERVER['DOCUMENT_ROOT'] . '/tp/enquiries/enquiries.json';

				file_put_contents($json_file, $json_array, FILE_APPEND | LOCK_EX);


			} else {
				$errors[] = 'Your enquiry has not been sent, please try again';
			}
		}

	}

$target_page = false;

$send_to = config('company_email');
$company_name = config('company_name');

$errors  = array();
$posted  = false;
$success = false;

$current_url = (isset($_POST['page']) && !empty($_POST['page'])) ? $_POST['page'] : 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

# is this the normal or quick form?
$quick = (isset($_POST['type']) && $_POST['type'] == 'quick') ? true : false;

# set up the common fields
$send_data = array();
$send_data['name']    = (isset($_POST['name']) && !empty($_POST['name'])) ? $_POST['name'] : '';
$send_data['email']   = (isset($_POST['email']) && !empty($_POST['email'])) ? $_POST['email'] : '';

# if this is not the quick form then add the additional fields
if (!$quick) {
    $send_data['tel'] = (isset($_POST['tel']) && !empty($_POST['tel'])) ? $_POST['tel'] : '';
}

$send_data['message'] = (isset($_POST['message']) && !empty($_POST['message']) && $_POST['message'] != ' ') ? $_POST['message'] : '';

# check if the form has been submitted
if (isset($_POST['bts']) && $_POST['bts'] == '') {

    # the form has been posted
    $posted = true;

    # check the name value
    if ($send_data['name'] == '') {
        $errors[] = 'Please fill in your name';
    }

    # check the email value
    if ($send_data['email'] == '') {
        $errors[] = 'Please fill in your email address';
    } else {
        # validate the email
        $validate_email = filter_var($send_data['email'], FILTER_VALIDATE_EMAIL);
        if (!$validate_email) {
            $errors[] = 'Please check your email address is correct';
        } else {
            # check the domains MX records
            if(!checkdnsrr(array_pop(explode("@",$send_data['email'])),"MX")){
                $errors[] = 'Please use a valid email address';
            }
        }
    }

    # if this is not the quick form then check the additional fields
    if (!$quick) {
        if (strlen($send_data['tel']) < 10) {
            $errors[] = 'Please add a valid telephone number!';
        }
    }

    # check the message
    if ($send_data['message'] == '') {
        $errors[] = 'Please fill in a message';
    }

    # if there are no errors then send the message
    if (count($errors) == 0) {

        $send_from = $send_data['name']  . "<" . $send_data['email']  . ">";

        $subject = 'Enquiry From Website ' . $_SERVER['HTTP_HOST'];

        $email_message = 'Below are the details that have been submitted on your contact form' . "\n\n";

        $email_message .= '________________________________________' . "\n\n";

        if (count($send_data) > 0) {
            foreach ($send_data as $key => $value) {
                $email_message .= $key . ' : ' . htmlspecialchars($value) . "\n";
            }
        }

        $email_message .= '________________________________________' . "\n\n";

        $email_message .= 'IP : ' . $_SERVER["REMOTE_ADDR"] . "\n\n";
        $email_message .= 'URL : ' . $current_url . "\n\n";
        $email_message .= 'WUKmedia | http://wukmedia.uk';

        #$headers = "From: " . strip_tags($send_from) . "\r\n";
        #$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
        #$headers .= "MIME-Version: 1.0\r\n";
        #$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

        if (mail($send_to, $subject, $email_message, "From: " . $send_from)) {
            $success = true;

            # now that the enquiry has been sent we can confirm to user
            $FromCompany    =  $company_name . "<" . $send_to . ">";
            $thanks_email   =  "Thank you for your enquiry " . $send_data['name'] . ".\n";
            $thanks_email   .=  "We will be back in touch with you shortly, \n\n";
            $thanks_email   .=  $company_name . "\n";
            $thanks_email   .=  'http://' . $_SERVER['HTTP_HOST'] . "\n\n\n";

            mail($send_data['email'], "Thanks for the Enquiry", $thanks_email, "From: " . $send_from);

            # now store the data in a json array
            $send_data['ip'] = $_SERVER["REMOTE_ADDR"];
            $send_data['timestamp'] = time();

            $json_array = "\n" . json_encode($send_data);

            $json_file = $_SERVER['DOCUMENT_ROOT'] . '/tp/enquiries/enquiries.json';

            file_put_contents($json_file, $json_array, FILE_APPEND | LOCK_EX);


        } else {
            $errors[] = 'Your enquiry has not been sent, please try again';
        }
    }

}

【问题讨论】:

    标签: php html forms validation checkbox


    【解决方案1】:

    在验证我编写的表单时,我只使用 Recaptcha。这是您的选择吗?如果是,那么您需要该站点处于活动状态,以便您可以访问该站点的域名。

    要开始这个,请转到:https://www.google.com/recaptcha/intro/v3beta.html

    获取 SITEKEY 和 SECERTKEY - 他们一步一步(非常简单)了解如何访问这两个密钥。

    一旦你在头标签中只有一小段代码,就像这样:

     <head>
       <script src='https://www.google.com/recaptcha/api.js'></script>
    </head> 
    

    之后,您只需将代码添加到表单标签中,如下所示:

    <form>
    <!-- put this wherever you want it in the form - usually at the bottom -->
    <div class="g-recaptcha" data-sitekey="<!-- Site Key HERE -->"></div>
    </form>
    

    然后最后在处理表单数据的 PHP 代码中对其进行授权,例如:

    $captcha = $_POST["g-recaptcha-response"]; // Declare variable 
    if(isset($_POST['g-recaptcha-response'])){
             $captcha=$_POST['g-recaptcha-response'];
    
        }
    
    
    if(!$captcha){
    
        header("Location: <!-- Error HTML page OR echo and error statement -->");
        exit; 
        }
    
    $secretKey = "<!-- SECRET KEY HERE -->";
    $ip = $_SERVER['REMOTE_ADDR'];
    $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
    $responseKeys = json_decode($response, true); 
    if(intval($responseKeys["success"]) !== 1) {
    
        echo '<h2>Spam Detected</h2>';
    
        }
    
        else {
    
            header("Location: <!-- Thank you HTML page OR echo and thanks statement -->");
    
            }
    

    你会看到我已经评论了网站和密钥的去向。

    【讨论】:

      【解决方案2】:

      只需将required 放在标签复选框上。例如:

      <input type="checkbox" name="" value="" required> text 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-06
        • 2012-10-01
        • 1970-01-01
        • 2014-03-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多