2016-12-07 208 views
4

我將Google Recaptcha集成到了我的網站。Google reCAPTCHA無法正常工作

但是,人們仍然可以填寫表單併發送郵件,而無需完成驗證碼。 (所以他們不必解決任何他們可以直接通過的謎題,當然這使我可以自由地運行機器人)

所以,我基本上需要PHP代碼來檢查用戶是否實際上「滴答」或「完成」了Recaptcha。那麼他們可以繼續發送郵件。

這裏是我的PHP表單代碼:

<!-- Start Contact Form --> 

<div id="contact-form" class="contatct-form"> 
<div class="loader"></div> 
<form method="post" action="mail.php"> 
<div class="row"> 
<div class="col-md-4"> 
<label for="name">Name<span class="required">*</span></label> 
<span class="name-missing">Please enter your name</span> 
<input id="name" name="name" type="text" value="" size="60"> 
</div> 
<div class="col-md-4"> 
<label for="e-mail">Email<span class="required">*</span></label> 
<span class="email-missing">Please enter a valid e-mail</span> 
<input id="e-mail" name="email" type="text" value="" size="60"> 
</div> 
<div class="col-md-4"> 
<label for="url">Website</label> 
<input id="url" name="url" type="text" value="" size="80"> 
</div> 
</div> 
<div class="row"> 
<div class="col-md-12"> 
<label for="message">Add Your Comment</label> 
<span class="message-missing">Say something!</span> 
<textarea id="message" name="message" cols="45" rows="10"></textarea> 
</br> 
<!--Google reCAPTCHA--> 
<?php 
require_once('recaptchalib.php'); 
$publickey = "My Public Key"; // you got this from the signup page 
echo recaptcha_get_html($publickey); 
?> 
<!--End Google reCAPTCHA--> 
<input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" onclick="return valtest();"> 
</div> 
</div> 
</form> 

這裏是我的mail.php代碼:

<?php 
require_once('recaptchalib.php'); 
$privatekey = "My private key"; 
$resp = recaptcha_check_answer ($privatekey, 
          $_SERVER["REMOTE_ADDR"], 
          $_POST["recaptcha_challenge_field"], 
          $_POST["recaptcha_response_field"]); 
if (!$resp->is_valid) { 
    // What happens when the CAPTCHA was entered incorrectly 
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." . 
    "(reCAPTCHA said: " . $resp->error . ")"); 
} else { 
    $sendto = "[email protected]"; 
$name=$_REQUEST['name']; 
$usermail = $_REQUEST['email']; 
$url=$_REQUEST['url']; 
$content = nl2br($_POST['message']); 
$subject = "Web Enquiry"; 
$headers = "From: " . strip_tags($name) . "\r\n"; 
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n"; 
$headers .= "MIME-Version: 1.0\r\n"; 
$headers .= "Content-Type: text/html;charset=utf-8 \r\n"; 
$msg = "<html><body style='font-family:Arial,sans-serif;'>"; 
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New Enquiry</h2>\r\n"; 
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n"; 
$msg .= "<p><strong>Client Name:</strong> ".$name."</p>\r\n"; 
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n"; 
$msg .= "<p><strong>Contact:</strong> ".$url."</p>\r\n"; 
$msg .= "</body></html>"; 
mail($sendto, $subject, $msg, $headers); 
echo "<script>window.location =\"index.php\";</script>"; 

這裏是recaptchalib.php代碼:

<?php 
/** 
* This is a PHP library that handles calling reCAPTCHA. 
* - Documentation and latest version 
*   https://developers.google.com/recaptcha/docs/php 
* - Get a reCAPTCHA API Key 
*   https://www.google.com/recaptcha/admin/create 
* - Discussion group 
*   http://groups.google.com/group/recaptcha 
* 
* @copyright Copyright (c) 2014, Google Inc. 
* @link  http://www.google.com/recaptcha 
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy 
* of this software and associated documentation files (the "Software"), to deal 
    * in the Software without restriction, including without limitation the rights 
    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
    * copies of the Software, and to permit persons to whom the Software is 
    * furnished to do so, subject to the following conditions: 
    * 
    * The above copyright notice and this permission notice shall be included in 
    * all copies or substantial portions of the Software. 
    * 
    * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
     * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
     * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
     * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
     * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
     * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
     * THE SOFTWARE. 
      */ 
      /** 
      * A ReCaptchaResponse is returned from checkAnswer(). 
      */ 
      class ReCaptchaResponse 
      { 
      public $success; 
      public $errorCodes; 
       } 
       class ReCaptcha 
       { 
       private static $_signupUrl = "https://www.google.com/recaptcha/admin"; 
        private static $_siteVerifyUrl = 
        "https://www.google.com/recaptcha/api/siteverify?"; 
        private $_secret; 
       private static $_version = "php_1.0"; 
       /** 
* Constructor. 
* 
* @param string $secret shared secret between site and ReCAPTCHA server. 
*/ 
function ReCaptcha($secret) 
{ 
    if ($secret == null || $secret == "") { 
     die("To use reCAPTCHA you must get an API key from <a href='" 
      . self::$_signupUrl . "'>" . self::$_signupUrl . "</a>"); 
    } 
    $this->_secret=$secret; 
} 
/** 
* Encodes the given data into a query string format. 
* 
* @param array $data array of string elements to be encoded. 
* 
* @return string - encoded request. 
*/ 
private function _encodeQS($data) 
{ 
    $req = ""; 
    foreach ($data as $key => $value) { 
     $req .= $key . '=' . urlencode(stripslashes($value)) . '&'; 
    } 
    // Cut the last '&' 
    $req=substr($req, 0, strlen($req)-1); 
    return $req; 
} 
/** 
* Submits an HTTP GET to a reCAPTCHA server. 
* 
* @param string $path url path to recaptcha server. 
* @param array $data array of parameters to be sent. 
* 
* @return array response 
*/ 
private function _submitHTTPGet($path, $data) 
    { 
    $req = $this->_encodeQS($data); 
    $response = file_get_contents($path . $req); 
    return $response; 
    } 
    /** 
    * Calls the reCAPTCHA siteverify API to verify whether the user passes 
    * CAPTCHA test. 
    * 
    * @param string $remoteIp IP address of end user. 
    * @param string $response response string from recaptcha verification. 
    * 
    * @return ReCaptchaResponse 
    */ 
    public function verifyResponse($remoteIp, $response) 
    { 
    // Discard empty solution submissions 
    if ($response == null || strlen($response) == 0) { 
     $recaptchaResponse = new ReCaptchaResponse(); 
     $recaptchaResponse->success = false; 
     $recaptchaResponse->errorCodes = 'missing-input'; 
     return $recaptchaResponse; 
    } 
    $getResponse = $this->_submitHttpGet(
     self::$_siteVerifyUrl, 
     array (
      'secret' => $this->_secret, 
      'remoteip' => $remoteIp, 
      'v' => self::$_version, 
      'response' => $response 
     ) 
    ); 
    $answers = json_decode($getResponse, true); 
    $recaptchaResponse = new ReCaptchaResponse(); 
    if (trim($answers ['success']) == true) { 
     $recaptchaResponse->success = true; 
    } else { 
     $recaptchaResponse->success = false; 
     $recaptchaResponse->errorCodes = $answers [error-codes]; 
    } 
    return $recaptchaResponse; 
    } 
} 
?> 

當我更換

 <!--Google reCAPTCHA--> 
     <?php 
     require_once('recaptchalib.php'); 
     $publickey = "My Site Key"; // you got this from the signup page 
     echo recaptcha_get_html($publickey); 
     ?> 
     <!--End Google reCAPTCHA--> 

   <!--Google reCAPTCHA--> 
      <div class="g-recaptcha" data-sitekey="My Site key"></div> 
      <!--End Google reCAPTCHA--> 

它會顯示小工具,但人們仍然可以填寫表格,並沒有完成驗證碼發送郵件。你有

+1

'
'是不是關閉標籤 – Blueblazer172

+0

谷歌已經改變了一些代碼功能在V2中,你必須使用它們也 – Blueblazer172

+0

張貼截圖你是如何得到出put – Gattsu

回答

2

首先要檢查的ReCaptcha isset:

<?php 

$errMsg = ""; 
$succMsg = ""; 

/**************************/ 
/* GOOGLE reCAPTCHA START */ 
/**************************/ 
require_once '../../reCAPTCHA/autoload.php'; 
$siteKey = 'sitekey'; 
$secret = 'secretkey'; 
/************************/ 
/* GOOGLE reCAPTCHA END */ 
/************************/ 

if ((isset($_POST['submit']) | !empty($_POST["submit"]))) { 

    if ((isset($_POST['g-recaptcha-response'])) && !empty($_POST["g-recaptcha-response"])) { 

     $recaptcha = new \ReCaptcha\ReCaptcha($secret); 
     $resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']); 
     if ($resp->isSuccess()) { 

      $succMsg = "Success Message"; 

      /** 
      * DO THE DB ENTRIES HERE 
      */ 

     } 

    } else { 

     $errMsg = "Error With Captcha"; 
    } 
} 
?> 

,你會從谷歌需要these文件。
他們在這裏下載:require_once '../../reCAPTCHA/autoload.php';

表單頁面看起來應該像:

<head> 
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 

    <script src="https://www.google.com/recaptcha/api.js" async defer></script> 
</head> 
<div id="contact-form" class="contatct-form"> 
    <div class="loader"></div> 
    <form method="post"> 
     <div class="row"> 
      <?php 
       if (isset($succMsg)) { 
        echo $succMsg; 
       } else { 
        echo ""; 
       } 
       if (isset($errMsg)) { 
        echo $errMsg; 
       } else { 
        echo ""; 
       } 
      ?> 
      <div class="col-md-4"> 
       <label for="name">Name<span class="required">*</span></label> 
       <span class="name-missing">Please enter your name</span> 
       <input id="name" name="name" type="text" value="" size="60"> 
      </div> 
      <div class="col-md-4"> 
       <label for="e-mail">Email<span class="required">*</span></label> 
       <span class="email-missing">Please enter a valid e-mail</span> 
       <input id="e-mail" name="email" type="text" value="" size="60"> 
      </div> 
      <div class="col-md-4"> 
       <label for="url">Website</label> 
       <input id="url" name="url" type="text" value="" size="80"> 
      </div> 
     </div> 
     <div class="row"> 
      <div class="col-md-12"> 
       <label for="message">Add Your Comment</label> 
       <span class="message-missing">Say something!</span> 
       <textarea id="message" name="message" cols="45" rows="10"></textarea> 
       <br> 
       <div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>"></div> 
       <input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" onclick="return valtest();"> 
      </div> 
     </div> 
    </form> 
</div> 
+0

評論是不適合擴展討論;此對話已被[轉移到聊天](http://chat.stackoverflow.com/rooms/130103/discussion-on-answer-by-blueblazer172-google-recaptcha-is-not-working)。 –

0

這是我的聯繫頁面:

<!doctype html> 
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> 
<!--[if (gte IE 9)|!(IE)]><html lang="en" class="no-js"> <![endif]--> 
<html lang="en"> 
<head> 
<!-- Basic --> 
<title> </title> 
<!-- Define Charset --> 
<meta charset="utf-8"> 
<!-- Responsive etatag --> 
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> 
<!-- Page Description--> 
<meta name="Description""> 
<meta name="keywords" "> 
<META NAME="ROBOTS" CONTENT="INDEX, FOLLOW"> 
<meta name="author" content=" "> 
<meta name="googlebot" content="noodp"> 
<link rel="canonical" href=" "/> 
<!-- CSS Styles --> 
<?php 
?> 
<!-- CSS Styles END--> 
<script type="text/javascript"> 
function valtest() 
{ 
var name=document.getElementById('name').value; 
var email=document.getElementById('e-mail').value; 
var url=document.getElementById('url').value; 
var message=document.getElementById('message').value; 
if((name==null||name=="")) 
{ 
alert("Please Enter Name"); 
return false; 
} 
if((email==null||email=="")) 
{ 
alert("Please Enter email"); 
return false; 
} 
else 
{ 
alert('Thank you for Send The Details'); 

return true; 
} 
} 
</script> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> 

<script src="https://www.google.com/recaptcha/api.js" async defer></script> 
</head> 
<body oncontextmenu="return false" ondragstart="return false" onselectstart="return false"> 
<!-- Container --> 
<div id="container"> 
<!-- Start Header --> 
<div class="hidden-header"></div> 
<header class="clearfix"> 
<!-- Start Top Bar --> 
<?php include_once(); ?> 
<!-- End Top Bar --> 
<!-- Start Header (Logo & Naviagtion) --> 
<div class="navbar navbar-default navbar-top"> 
<div class="container"> 
<div class="navbar-header"> 
<!-- Stat Toggle Nav Link For Mobiles --> 
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> 
<i class="fa fa-bars"></i> 
</button> 
<!-- End Toggle Nav Link For Mobiles --> 
<a class="navbar-brand" href="index.php"><img alt="" src="images/margo.png"></a> 
</div> 
<div class="navbar-collapse collapse"> 
<!-- Start Navigation List --> 
<!-- End Navigation List --> 
</div> 
</div> 
</div> 
<!-- End Header (Logo & Naviagtion) --> 
</header> 
<!-- End Header --> 
<!-- Start Page Banner --> 
<!-- End Page Banner --> 
<!-- Start Content --> 
<div id="content"> 
<div class="container"> 
<div class="page-content"> 
<div class="col-md-8"> 
<!-- Classic Heading --> 
<h4 class="classic-title"><span>Contact Us</span></h4> 
<!-- Start Contact Form --> 
<div id="contact-form" class="contatct-form"> 
<div class="loader"></div> 
<form method="post"> 
<div class="row"> 
<?php 
if (isset($succMsg)) { 
echo $succMsg; 
} else { 
echo ""; 
} 
if (isset($errMsg)) { 
echo $errMsg; 
} else { 
echo ""; 
} 
?> 
<div class="col-md-4"> 
<label for="name">Name<span class="required">*</span></label> 
<span class="name-missing">Please enter your name</span> 
<input id="name" name="name" type="text" value="" size="60"> 
</div> 
<div class="col-md-4"> 
<label for="e-mail">Email<span class="required">*</span></label> 
<span class="email-missing">Please enter a valid e-mail</span> 
<input id="e-mail" name="email" type="text" value="" size="60"> 
</div> 
<div class="col-md-4"> 
<label for="url">Website</label> 
<input id="url" name="url" type="text" value="" size="80"> 
</div> 
</div> 
<div class="row"> 
<div class="col-md-12"> 
<label for="message">Add Your Comment</label> 
<span class="message-missing">Say something!</span> 
<textarea id="message" name="message" cols="45" rows="10"></textarea> 
<br> 
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>"></div> 
<input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" onclick="return valtest();"> 
</div> 
</div> 
</form> 
</div> 
<br/> 
<!-- End Contact Form --> 
</div> 

<div class="col-md-4"> 

<!-- Classic Heading --> 
<h4 class="classic-title"><span>Head Office</span></h4> 

<!-- Divider --> 
<div class="hr1" style="margin-bottom:10px;"></div> 

<!-- Info - Icons List --> 
<ul class="icons-list"> 
</ul> 

<div class="hr1" style="margin-bottom:50px;"></div> 
</div> 
</div> 
</div> 
</div> 
</div> 
</div> 
</div> 
<!-- End content --> 
<!-- Start Map --> 
<!-- End Map --> 
<!-- Start Footer --> 
<?php 
include_once('footer.php'); 
?> 
<!-- End Footer --> 
</div> 
<!-- End Container --> 
<!-- Go To Top Link --> 
<a href="#" class="back-to-top"><i class="fa fa-angle-up"></i></a> 
<div id="loader"> 
<div class="spinner"> 
<div class="dot1"></div> 
<div class="dot2"></div> 
</div> 
</div> 
</body> 
</html> 
+0

你應該刪除那個答案,因爲它沒有。把這個內容放在你的問題中。 – Blueblazer172