使用formhandler.php获取ReCaptcha的问题

时间:2018-05-31 09:58:57

标签: php recaptcha

我试图在表单中添加ReCaptcha。我使用formhandler.phperror.phpsuccess.php页面。

我已经把这段代码

 <?php  
if(isset($_POST['submit'])){
    $url = 'https://google.com/recaptcha/api/siteverify';
    $privatekey = "xxx";

    $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);

    $data = json_decode($response);

    if(isset($data->success) AND $data->success==true) {

        header('Location: success.php');

    }else{
        header('Location: error.php?CaptchaFail=True');

    }
}
?>

进入我的formhandler.php。如果我没有勾选ReCaptcha,我的error.php就可以了。但如果我使用ReCaptcha,我仍然会收到错误页面。

我不擅长php,我想我在某处犯了错误。

这是我使用的formhandler.php的完整代码:

<?php
if(isset($_POST['email'])) {
    $url = 'https://google.com/recaptcha/api/siteverify';
    $privatekey = "xxxx";

    $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);

    $data = json_decode($response);

    $email_to = "xxx";
    $email_subject = "Kontaktanfrage - ec-parts.de";     

    $email = $_POST['email'];
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $message = $_POST['message'];
    $checkboxaccept = $_POST['checkboxaccept'];

    $email_message = "Nachricht:\n\n";

    function clean_string($string) { 
      $bad = array("content-type","bcc:","to:","cc:","href"); 
      return str_replace($bad,"",$string);
    }

    function getUserIpAddr()
    {
        if (!empty($_SERVER['HTTP_CLIENT_IP']))
        {
            return $_SERVER['HTTP_CLIENT_IP'];
        }
        else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
        {
            return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else
        {
            return $_SERVER['REMOTE_ADDR'];
        }
    }    

    $email_message .= "Name: ".clean_string($name)."\n";
    $email_message .= "Email: ".clean_string($email)."\n";
    $email_message .= "Telefon: ".clean_string($phone)."\n";
    $email_message .= "Nachricht: ".clean_string($message)."\n";

    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/plain;charset=UTF-8" . "\r\n";
    $headers .= 'From: '.$email. "\r\n";

    if (@mail($email_to, $email_subject, $email_message, $headers, $checkboxaccept, $response))
    if (isset($data->success) AND $data->success==true) {
        header('Location: success.php');
    } else {
        header('Location: error.php?CaptchaFail=True');
    }
} 
?>

也许是因为代码if (isset($data->success) AND $data->success==true)。我不知道该把它放在哪里。我还是PHP的初学者......

我只想formhandler.php检查我是否使用了ReCaptcha。我搜索了很多不同的代码,但这个代码几乎可以工作。

如果需要,您可以在此处测试表单:contact form

修改

我已使用此post的解决方案更改了代码:

我的formhandler.php

<?php

function validate_email_address($email = false) {
    return (preg_match('/^[^@\s]+@([-a-z0-9]+\.)+[a-z]{2,}$/i', $email))? true : false;
}

function remove_email_injection($field = false) {
    return (str_ireplace(array("\r", "\n", "%0a", "%0d", "Content-Type:", "bcc:","to:","cc:"), '', $field));
}

// Set email variables
$email_to = "xxx";
$email_subject = "Kontaktanfrage - ec-parts.de";     

// Set required fields
$required_fields = array('email', 'name', 'message', 'checkboxaccept');

// set error messages
$error_messages = array(
    'email' => 'Bitte geben Sie eine gültige E-mailadresse an.',
    'name' => 'Bitte geben Sie Ihren Namen an.',
    'message' => 'Bitte schreiben Sie uns, worum es in Ihrer Anfrage geht.',
    'checkboxaccept' => 'Bitte klicken Sie die Checkbox an, wenn Sie fortsetzen wollen.'
);

// Set form status
$form_complete = FALSE;

// configure validation array
$validation = array();

// boolean variable to validate recaptcha
$valid_recaptcha = false;

if(isset($_POST['submit'])){
    // First validate recaptcha

    $url = 'https://www.google.com/recaptcha/api/siteverify';
    $privatekey = "xxx";
    $response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADDR']);
    $data = json_decode($response);
    if($data->success) {
        $valid_recaptcha = true;
    }

    if($valid_recaptcha){

        // now process your form here. sanitize and validate input fields

        // Sanitise POST array
        foreach($_POST as $key => $value){
            $_POST[$key] = remove_email_injection(trim($value));
        }

        // Loop into required fields and make sure they match our needs
        foreach($required_fields as $field) {       

            // the field has been submitted?
            if(!array_key_exists($field, $_POST)){
                array_push($validation, $field);
            }

            // check there is information in the field?
            if($_POST[$field] == ''){
                array_push($validation, $field);
            }

            // validate the email address supplied
            if($field == 'email'){
                if(!validate_email_address($_POST[$field])){
                    array_push($validation, $field);
                }
            }

        }

        // basic validation result
        if(count($validation) == 0) {

            // Prepare our content string
            $email_content = 'Neue Kontaktanfrage: ' . "\n\n";

            // simple email content
            foreach($_POST as $key => $value){
                if($key != 'submit' && $key != 'g-recaptcha-response') $email_content .= $key . ': ' . $value . "\n";

            }

            // if validation passed ok then send the email
            mail($email_to, $email_subject, $email_content);

            // Update form switch
            $form_complete = TRUE;

        }

    }
}

?>

我的kontakt.php

<!DOCTYPE html>
<html >
<head>
  <!-- Site made with Mobirise Website Builder v4.5.2, https://mobirise.com -->
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="generator" content="Mobirise v4.5.2, mobirise.com">
  <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
  <link rel="shortcut icon" href="assets/images/favicon-1.gif" type="image/x-icon">
  <meta name="description" content="ec - exclusive carparts GmbH Berlin, Der Tuning Spezialist aus Berlin. Kontaktdaten.">
  <title>ec - exclusive carparts GmbH Berlin. Kontakt. T&Uuml;V- Profi, Brabus H&auml;ndler Berlin.</title>
  <link rel="stylesheet" href="assets/bootstrap-material-design-font/css/material.css">
  <link rel="stylesheet" href="assets/et-line-font-plugin/style.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat:400,700">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway:100,100i,200,200i,300,300i,400,400i,500,500i,600,600i,700,700i,800,800i,900,900i">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,700,400italic,700italic&subset=latin">
  <link rel="stylesheet" href="assets/tether/tether.min.css">
  <link rel="stylesheet" href="assets/bootstrap/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/soundcloud-plugin/style.css">
  <link rel="stylesheet" href="assets/dropdown/css/style.css">
  <link rel="stylesheet" href="assets/theme/css/style.css">
  <link rel="stylesheet" href="assets/mobirise3-blocks-plugin/css/style.css">
  <link rel="stylesheet" href="assets/mobirise/css/mbr-additional.css" type="text/css">


  <meta name="rating" content="General" />
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <meta name="language" content="de" />
        <meta name="keywords" content="exclusive carparts Berlin,ec-parts,Kontakt,Berlin" />
        <meta name="publisher" content="Website by inventmedia. http://www.inventmedia.de" />
        <meta name="robots" content="all,index,follow" />
        <script src='https://www.google.com/recaptcha/api.js'></script>
</head>
<body>
<section id="menu-3g" data-rv-view="463">

    <nav class="navbar navbar-dropdown navbar-fixed-top">
        <div class="container">

            <div class="mbr-table">
                <div class="mbr-table-cell">

                    <div class="navbar-brand">
                        <a href="http://www.ec-parts.de" class="navbar-logo"><img src="assets/images/ecparts-logo-menu-big-520x128.png" alt="ec - exclusive carparts Berlin" title="ec - exclusive carparts Berlin"></a>

                    </div>

                </div>
                <div class="mbr-table-cell">

                    <button class="navbar-toggler pull-xs-right hidden-md-up" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar">
                        <div class="hamburger-icon"></div>
                    </button>

                    <ul class="nav-dropdown collapse pull-xs-right nav navbar-nav navbar-toggleable-sm" id="exCollapsingNavbar"><li class="nav-item"><a class="nav-link link" href="index.php">STARTSEITE</a></li><li class="nav-item dropdown"><a class="nav-link link" href="auto-folierung-fahrzeug-komplettbeklebung-berlin.php" aria-expanded="false">FOLIERUNG</a></li><li class="nav-item dropdown"><a class="nav-link link" href="portfolio.php" aria-expanded="false">PORTFOLIO</a></li><li class="nav-item"><a class="nav-link link" href="service-partner.php" aria-expanded="false">SERVICE &amp; PARTNER</a></li>
                    <li class="nav-item"><a class="nav-link link" href="tuev-sondereintragung.php" aria-expanded="false">T&Uuml;V</a></li><li class="nav-item"><a class="nav-link link" href="produkte.php" aria-expanded="false">PRODUKTE &amp; LEISTUNGEN</a></li><li class="nav-item"><a class="nav-link link" href="kontakt.php" aria-expanded="false">KONTAKT</a></li></ul>
                    <button hidden="" class="navbar-toggler navbar-close" type="button" data-toggle="collapse" data-target="#exCollapsingNavbar">
                        <div class="close-icon"></div>
                    </button>

                </div>
            </div>

        </div>
    </nav>

</section>

<section class="engine"><a href="https://mobirise.co/a">web builder</a></section><section class="mbr-section article mbr-parallax-background mbr-after-navbar" id="msg-box8-3h" data-rv-view="465" style="background-image: url(assets/images/start-2-836x576.jpg); padding-top: 200px; padding-bottom: 200px;">

    <div class="mbr-overlay" style="opacity: 0.5; background-color: rgb(34, 34, 34);">
    </div>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2 text-xs-center">



            </div>
        </div>
    </div>

</section>

<div id="header3-3i" custom-code="true" data-rv-view="468"><section class="mbr-section mbr-section__container article" data-rv-view="1005" style="background-color: rgb(239, 239, 239); padding-top: 20px; padding-bottom: 20px;">
    <div class="container">
        <div class="row">
            <div class="col-xs-12">
                <h1 class="card-header mbr-editable-content" style="text-align: left; font-family: Oswald, sans-serif; font-size: 32px; color: rgb(34, 34, 34);">Kontakt</h1>

            </div>
        </div>
    </div>
</section></div>

<div id="content6-3o" custom-code="true" data-rv-view="469"><section class="mbr-section article mbr-section__container" data-rv-view="327" style="background-color: rgb(239, 239, 239); padding-top: 20px; padding-bottom: 20px; border-bottom: 1px solid #ccc;">

    <div class="container">
        <div class="row">
            <div class="col-xs-12 col-md-6 lead mbr-editable-full"><p><strong>ec exclusive carparts GmbH
</strong></p>
            <p>Gesch&auml;ftsf&uuml;hrer: Mirko Schr&ouml;ter
</p>
            <p>Bl&uuml;cherstrasse 60
</p><p>10961 Berlin</p><p><br></p><p>Fon: +49 (0) 30 36 40 67 36
</p><p>Fax: +49 (0) 30 36 40 67 35
</p><p>Internet: <a href="http://www.ec-parts.de" target="_blank">www.ec-parts.de</a>
</p><p>E-Mail: <a href="mailto:info@ec-parts.de">info@ec-parts.d</a>e</p></div>
            <div class="col-xs-12 col-md-6 lead mbr-editable-full">
<p><strong>&Ouml;ffnungszeiten: </strong>
</p><p>Mo. - Fr.: 10 Uhr - 18.30 Uhr 
</p><p>Sa.: nach Vereinbarung</p></div>
        </div>
    </div>

</section></div>

<section class="mbr-section extForm1 mbr-parallax-background" id="extForm1-5m" data-rv-view="470" style="background-image: url(assets/images/folierung-836x576.jpg); padding-top: 50px; padding-bottom: 50px;">

    <div class="mbr-overlay" style="opacity: 0.8; background-color: rgb(255, 255, 255);">
    </div>

    <div class="mbr-table mbr-table-full">
        <div class="mbr-table-cell">

            <div class="container">
                <div class="row">
                    <div class="mbr-table-md-up">




                        <!-- & -->

                        <div class="mbr-table-cell col-md-7 text-xs-center text-md-left">

                                <h2 class="display-2 h-black"><span style="font-weight: normal;">Kontaktformular</span></h2>
<?php
    if(isset($_POST['submit'])){
        if(!$valid_recaptcha){
            // error
            ?>
                <div class="col-md-12" style="margin-left: 200px;" align="center">ReCAPTCHA fehlgeschlagen, bitte versuchen Sie es erneut.</div><br />
            <?php
        }
    }
   ?>                             
                             <div class="col-md-12" style="padding-left: 0px; padding-right: 0px;">

                                    <?php if($form_complete === FALSE): ?>
                                    <form action="formhandler.php" method="post">


                                            <div class="col-xs-6">
                                                 <input type="text" class="form-control" name="name" required data-form-field="Name" placeholder="Name*" value="<?php echo     isset($_POST['name'])? $_POST['name'] : ''; ?>" /><?php if(in_array('name',    $validation)): ?><span class="error"><?php echo $error_messages['name']; ?>        </span><?php endif; ?>
                                            </div>

                                            <div class="col-xs-6" style="padding-left: 15px"> 
                                                 <input type="text" class="form-control" name="email" required data-form-field="Email" placeholder="E-mail*" value="<?php echo     isset($_POST['email'])? $_POST['email'] : ''; ?>" /><?php if(in_array('email',    $validation)): ?><span class="error"><?php echo $error_messages['email']; ?>        </span><?php endif; ?>  
                                            </div>

                                            <div class="col-xs-12">
                                                 <input type="text" class="form-control" name="phone" required data-form-field="Phone" placeholder="Telefon*">
                                            </div>

                                            <div class="col-xs-12">
                                                <textarea class="form-control" name="message" rows="7" data-form-field="Message" style="resize:none" placeholder="Nachricht" value="<?php echo     isset($_POST['message'])? $_POST['message'] : ''; ?>" /><?php if(in_array('message',    $validation)): ?><span class="error"><?php echo $error_messages['message']; ?>        </span><?php endif; ?></textarea>
                                            </div>
                                      <div class="col-xs-12">
                                          <label class="lead">
                                            <p><input style="margin-bottom: 0;" type="checkbox" name="checkboxaccept" required value="<?php echo     isset($_POST['checkboxaccept'])? $_POST['checkboxaccept'] : ''; ?>" /><?php if(in_array('checkboxaccept',    $validation)): ?><span class="error"><?php echo $error_messages['checkboxaccept']; ?>        </span><?php endif; ?>
                                                <span style="color: #1f008f;">*</span>Ich   stimme zu, dass meine Angaben aus dem Kontaktformular zur Beant&shy;wortung meiner Anfrage erhoben und verar&shy;beitet werden. Die Daten werden nach   abge&shy;schlossener Bear&shy;beitung Ihrer Anfrage gel&ouml;scht.</p>

                                          <p><em>Hinweis: Sie k&ouml;nnen Ihre Einwilligung jederzeit f&uuml;r die Zukunft per E-Mail an <a href="mailto:info@ec-parts.de" title="info@ec-parts.de">info@ec-parts.de</a> widerrufen. Detaillierte Informationen zum Umgang mit Nutzerdaten finden Sie in unserer <a href="datenschutz.php" target="_blank" rel="noopener noreferrer" title="Datenschutzerkl&auml;rung">Datenschutzerkl&auml;rung</a>.</em></p></label>
                                          </div>
                                        <div class="col-xs-12"><div class="g-recaptcha" data-sitekey="6Lc1TlwUAAAAAMxGXW7AEsy3w5asFtZKi8cvtuxL"></div></div>
                                        <div class="col-xs-12 buttons_wrap" style="margin-top: 10px;"><button type="submit" class="btn btn-primary">Nachricht senden</button></div>
                                    </form>
                            <?php else: ?>

                            <div class="row">
                                <div class="col-md-12 parent">

                                        <div class="col-md-12 col-lg-12" style="padding: 0;">
                                            <div class="intro-box right" style="margin: 10px 0;">   

                                                <div class="content alert alert-success" style="padding: 10px 10px 10px 10px;">
                                                    <h4 class="text-right mbr-editable-content">Vielen Dank f&uuml;r Ihre Nachricht!</h4>

                                                    <p class="mbr-section-text lead mbr-editable-content">Wir werden uns umgehend bei Ihnen melden.</p>
                                                </div>

                                            </div>
                                        </div>
                                </div>
                            </div>

    <!--<script type="text/javascript">
        setTimeout('ourRedirect()',5000)
            function ourRedirect(){
            location.href='http://web6.server.inventmedia.de/ec/kontakt.php'
        }
    </script>-->

    <?php endif; ?>
                            </div>    

                        </div>
                        <div class="mbr-table mbr-valign-top col-md-5">
                            <div class="mbr-figure"><img src="assets/images/mirko-1000x961.jpg" class="img-thumbnail central-image"></div>
                        </div>

                    </div>
                </div>
            </div>

        </div>
    </div>

</section>

<section class="mbr-section mbr-section-nopadding" id="map1-51" data-rv-view="480">
    <div class="mbr-map"><iframe frameborder="0" style="border:0" src="https://www.google.com/maps/embed/v1/place?key=xxx&amp;q=place_id:ChIJ8TAx5OdQqEcRUK_4PR7srUk" allowfullscreen=""></iframe></div>
</section>

<section class="mbr-slider mbr-section mbr-section-nopadding carousel slide extTestimonials1 extTestimonials3 extTestimonials5" data-ride="carousel" data-keyboard="false" data-wrap="true" data-interval="5000" data-pause="false" id="extTestimonials5-3k" data-rv-view="482" style="background-color: rgb(255, 255, 255); padding-top: 0px; padding-bottom: 0px;">



    <div class="mbr-section__container mbr-section__container--middle">
        <div class="container">
            <div class="row">
                <div class="col-xs-12 text-xs-center">


                </div>
            </div>
        </div>
    </div>

    <div class="container boxed-slider">
        <div>

            <div class="carousel-inner" role="listbox" data-visible="6">
                <div class="carousel-item active">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="wrap-img"><a href="http://www.bastuck.de/"><img src="assets/images/bastuck-226x118.png" alt="Bastuck" title="Bastuck"></a></div>
                        </div>
                    </div>
                </div><div class="carousel-item">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="wrap-img"><a href="http://www.barracuda-wheels.com/"><img src="assets/images/barracuda-226x118.png" alt="Barracuda" title="Barracuda"></a></div>
                        </div>
                    </div>
                </div><div class="carousel-item">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="wrap-img"><a href="http://www.bbs.com/"><img src="assets/images/bbs-226x118.png" alt="BBS" title="BBS"></a></div>
                        </div>
                    </div>
                </div><div class="carousel-item">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="wrap-img"><a href="http://www.breyton.de/germany/index.php"><img src="assets/images/breyton-226x118.png" alt="Breyton" title="Breyton"></a></div>
                        </div>
                    </div>
                </div><div class="carousel-item">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="wrap-img"><a href="http://www.oz-racing.de/"><img src="assets/images/oz-226x118.png" alt="OZ Racing" title="OZ Racing"></a></div>
                        </div>
                    </div>
                </div><div class="carousel-item">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="wrap-img"><a href="http://www.h-r.com/" target="_blank"><img src="assets/images/hr-226x118.png" alt="H&amp;R" title="H&amp;R"></a></div>
                        </div>
                    </div>
                </div><div class="carousel-item">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="wrap-img"><a href="http://www.knfilters.com/"><img src="assets/images/kn-226x118.png" alt="K&amp;N" title="K&amp;N"></a></div>
                        </div>
                    </div>
                </div><div class="carousel-item">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="wrap-img"><a href="http://www.lowtec.de/"><img src="assets/images/lowtec-226x118.png" alt="Lowtec" title="Lowtec"></a></div>
                        </div>
                    </div>
                </div>
            </div>



        </div>
    </div>

</section>

<section class="mbr-section mbr-section-md-padding mbr-footer footer1" id="contacts1-3l" data-rv-view="510" style="background-color: rgb(34, 34, 34); padding-top: 90px; padding-bottom: 90px;">

    <div class="container">
        <div class="row">
            <div class="mbr-footer-content col-xs-12 col-md-3">
                <div><img src="assets/images/ec-parts-logo-big-128x165.png" alt="ec - exclusive carparts Berlin" title="ec - exclusive carparts Berlin"></div>
            </div>
            <div class="mbr-footer-content col-xs-12 col-md-3">
                <p><strong>EC-Parts</strong><br>
<a href="index.php" class="text-info">Startseite</a><br>
<a href="kontakt.php" class="text-info">Kontakt</a><br><a href="datenschutz.php" class="text-info">Datenschutz</a><br><a href="impressum.php" class="text-info">Impressum</a></p>
            </div>
            <div class="mbr-footer-content col-xs-12 col-md-3">
                <p><strong>Kontakt</strong><br>
Email: <a href="mailto:info@ec-parts.de" class="text-info">info@ec-parts.de</a><br>
Fon: +49 (0) 30 36 40 67 36<br>
Fax: +49 (0) 30 36 40 67 35<br><br>
&Ouml;ffnungszeiten:
<br>Mo. - Fr.: 10 Uhr - 18.30 Uhr
<br>Sa.: nach Vereinbarung<br></p>
            </div>
            <div class="mbr-footer-content col-xs-12 col-md-3">
                <p><strong>Anschrift</strong><a class="text-info" href="https://mobirise.com/"><br></a>ec exclusive carparts Berlin Autotuning<br>
                Bl&uuml;cherstrasse 60<br>10961 Berlin<br></p>
            </div>

        </div>
    </div>
</section>


  <script src="assets/web/assets/jquery/jquery.min.js"></script>
  <script src="assets/tether/tether.min.js"></script>
  <script src="assets/bootstrap/js/bootstrap.min.js"></script>
  <script src="assets/smooth-scroll/smooth-scroll.js"></script>
  <script src="assets/touch-swipe/jquery.touch-swipe.min.js"></script>
  <script src="assets/jarallax/jarallax.js"></script>
  <script src="assets/bootstrap-carousel-swipe/bootstrap-carousel-swipe.js"></script>
  <script src="assets/dropdown/js/script.min.js"></script>
  <script src="assets/theme/js/script.js"></script>
  <script src="assets/mobirise3-blocks-plugin/js/script.js"></script>


 <div id="scrollToTop" class="scrollToTop mbr-arrow-up"><a style="text-align: center;"><i class="mbr-arrow-up-icon"></i></a></div>
  </body>
</html>

我不确定,为什么这不起作用。我试图一步一步地复制整个代码。我可以看到成功消息,表格遗失。

0 个答案:

没有答案