Skip to content

[STICKY][Optional feature] ReCaptcha Support #665

Closed

Description

@tankerkiller125

I fully understand that we don't want any more features for the project. I am simply creating this to give people a concept of how to add ReCaptcha to their own pages.

Composer command (official google lib)
composer require google/recaptcha "~1.1"

Code to add to any pages you want a captcha (will use built in if recaptcha not enabled)

<?php if (Config::get('RECAPTCHA_ENABLED')) { ?>
<div class="g-recaptcha" data-sitekey="<?php echo Config::get('RECAPTCHA_SITEKEY'); ?>"></div>
<script src="https://www.google.com/recaptcha/api.js"></script>
<?php } else { ?>
<br><img id="captcha" src="<?php echo URL; ?>login/showCaptcha"/>
<br><input type="text" name="captcha" placeholder="Please enter above characters" required/>

<!-- quick & dirty captcha reloader -->
<a href="#" style="display: block; font-size: 11px; margin: 5px 0 15px 0; text-align: center" onclick="document.getElementById('captcha').src = '<?php echo URL; ?>login/showCaptcha?' + Math.random(); return false">Reload Captcha</a>
<?php } ?>

CaptchaModel Function (add anywhere you'd like)

public static function checkRecaptcha($gReCaptchaResponse) {
    $recaptcha = new \ReCaptcha\ReCaptcha(Config::get('RECAPTCHA_SECRET'));
    $resp = $recaptcha->verify($gReCaptchaResponse, Request::server('REMOTE_ADDR'));
     if($resp->isSuccess()) {
        return true;
    } else {
        return false;
    }
}

Part you put into your function that checks for captcha (again compatible with built in captcha)

if (Config::get('RECAPTCHA_ENABLED')) {
    if (!CaptchaModel::checkRecaptcha($captcha)) {
       Session::add('feedback_negative', Language::getText('captcha-wrong'));
       return false;
    }
} else {
   if (!CaptchaModel::checkCaptcha($captcha)) {
        Session::add('feedback_negative', Language::getText('captcha-wrong'));
        return false;
    }
}

And last but not least this will need to be added to the config array

'RECAPTCHA_ENABLED' => true,
'RECAPTCHA_SECRET' => 'xxxxxxxxx',
'RECAPTCHA_SITEKEY' => 'xxxxxxxxxx',

Activity

  1. panique commented on Jun 3, 2015

    @panique
    Owner

    AWWESOMEEE !! Thank you so much, this should definitly go into the project by default! I'll do this in the next weeks when there's some time! :)

  2. tankerkiller125 commented on Jun 3, 2015

    @tankerkiller125
    Author

    Your welcome. I might add that the Language::getText should be changed to the correct Text::get (I forgot to change it from my implemention)

  3. changed the title [-]ReCaptcha Support[/-] [+][feature] ReCaptcha Support[/+] on Jun 4, 2015
  4. changed the title [-][feature] ReCaptcha Support[/-] [+][STICKY][Optional feature] ReCaptcha Support[/+] on Jul 9, 2015
  5. JFJanssen commented on Jul 17, 2015

    @JFJanssen

    Thanks tankerkiller125!

    Would indeed be great to see as a standard feature, ESPECIALLY if the present, server-side generated code is left in the code base as an alternative, similar to the option regarding the use of a locally hosted avatar vs. the use of gravatar.com.

  6. mcanatalay commented on Jul 20, 2015

    @mcanatalay
    Contributor

    Thank you tankerkiller125 there was a cpu issue in my server side. I think this would help me much.

  7. tankerkiller125 commented on Jul 23, 2015

    @tankerkiller125
    Author

    @mcanatalay Not sure if it will help with CPU however it does reduce bandwidth (since verification and images come from google and not your server)

  8. mcanatalay commented on Jul 24, 2015

    @mcanatalay
    Contributor

    Well, what does use cpu is image creating process and maybe key creating. Taking them externally surely help.

  9. panique commented on Jul 24, 2015

    @panique
    Owner

    FYI this script uses the most simple and native image creation possible in PHP, and rendering a captcha takes 1/1000sec on a standard CPU on a standard $5 server, so this should not be a big problem. @mcanatalay Can I ask you if you are using this in a very high-traffic scenario ?

  10. mcanatalay commented on Jul 24, 2015

    @mcanatalay
    Contributor

    No. Simply pressing reload captcha gives me %10 of cpu level. It is only captcha related problem. First, I was tought it is about my "autoload.php" since I cannot use composer, but it is only happens when I press reload captcha.

  11. tankerkiller125 commented on Jul 24, 2015

    @tankerkiller125
    Author

    Currently Refactoring this system (Hopefully bring the entire system into one well bundled system that doesn't require a bunch of extra code in the HTML)

  12. afermon commented on Jul 26, 2015

    @afermon

    Hi, I'm using the code above. However, I get the error "Fatal error: Call to undefined method Request::server()" that probably if because of Request::server('REMOTE_ADDR') in chechRecaptcha function. Does anyone knows how to get the client IP? I'm not so experienced in php

    EDIT: I fixed it by adding the function public static function server($key) in request.php. There should be another if in RegistrationModel.php to ask for Request::post('g-recaptcha-response') instead of 'captcha' when ReCaptcha is active.

    Thanks

  13. tankerkiller125 commented on Jul 26, 2015

    @tankerkiller125
    Author

    Sorry about that I think I made the server function. Replace it with
    $_SERVER['REMOTE_ADDR']

    On Sat, Jul 25, 2015, 23:45 Alex Fermon notifications@github.com wrote:

    Hi, I'm using the code above. However, I get the error "Fatal error: Call
    to undefined method Request::server()" that probably if because of
    Request::server('REMOTE_ADDR') in chechRecaptcha function. Does anyone
    knows how to get the client IP? I'm not so experienced in php

    —
    Reply to this email directly or view it on GitHub
    #665 (comment).

  14. mcanatalay commented on Jul 26, 2015

    @mcanatalay
    Contributor

    Or you can add this function after cookie function in Request class.

        /**
         * gets/returns the value of a specific key of the SERVER super-global
         * @param mixed $key key
         * @return mixed the key's value or nothing
         */
        public static function server($key){
            if (isset($_SERVER[$key])) {
                return $_SERVER[$key];
            }
        }
  15. tankerkiller125 commented on Jul 30, 2015

    @tankerkiller125
    Author

    The google lib should do most of the work. Make sure you have your keys
    right?

    On Thu, Jul 30, 2015, 11:23 Lester MacDonald notifications@github.com
    wrote:

    First off... I am a HUGE fan! I just tried to implement the reCaptcha and
    I get it to display and also get the green check mark but when submitting
    the form it always says the feedback error "The entered captcha security
    characters were wrong". I have added the $_SERVER['REMOTE_ADDR'] In the
    CaptchaModel.php and was wondering if there was anything else that needed
    to be updated.

    —
    Reply to this email directly or view it on GitHub
    #665 (comment).

  16. videsignz commented on Aug 21, 2015

    @videsignz

    Love the idea here...I keep getting an error when submiting
    Fatal error: Class 'ReCaptcha\ReCaptcha' not found in....
    I do not have a ReCaptchaController so not sure what do :/

  17. tankerkiller125 commented on Aug 21, 2015

    @tankerkiller125
    Author

    @videsignz Please read the very fist post very clearly. The Controller I used was the CaptchaController you will need to add the function from the first post yourself. The code needed has been clearly laid out and should be simple to follow. So again please read the very first post in this issue.

  18. videsignz commented on Aug 21, 2015

    @videsignz

    Yeah, I did everything else, then looked back and saw composer require google/recaptcha "~1.1"
    What a dummy...

    I did assume on some level that all the pieces were here though....my bad

  19. tankerkiller125 commented on Aug 21, 2015

    @tankerkiller125
    Author

    @videsignz I've done that a couple times 😆

  20. videsignz commented on Aug 22, 2015

    @videsignz

    Well, after everything is installed...I am receiving the error missing-input-response and that's it...keys are right...in the docs it is looking for $_POST['g-recaptcha-response'] yet in the registration model it gets Request::post('captcha') so there needs to be another if statement here I think...I'll test it and post back here

  21. videsignz commented on Aug 22, 2015

    @videsignz

    Ok, so one last thing to make this work if anyone else is having issues....
    Go to RegistrationModel.php and look at the first function registerNewUser(){}

    It looks like this

            // TODO this could be written simpler and cleaner
            // clean the input
            $user_name = strip_tags(Request::post('user_name'));
            $user_email = strip_tags(Request::post('user_email'));
            $user_password_new = Request::post('user_password_new');
            $user_password_repeat = Request::post('user_password_repeat');
    
            // stop registration flow if registrationInputValidation() returns false (= anything breaks the input check rules)
            $validation_result = self::registrationInputValidation(Request::post('captcha'), $user_name, $user_password_new, $user_password_repeat, $user_email);
            if (!$validation_result) {
                return false;
            }

    We need it to be like this to determine the proper post name which depends on which captcha type you are using.

            // TODO this could be written simpler and cleaner
            // clean the input
            $user_name = strip_tags(Request::post('user_name'));
            $user_email = strip_tags(Request::post('user_email'));
            $user_password_new = Request::post('user_password_new');
            $user_password_repeat = Request::post('user_password_repeat');
    
                    // THIS IS THE SWITCH! :)
            if (Config::get('RECAPTCHA_ENABLED')) {
                $captcha = Request::post('g-recaptcha-response');
            }else{
                $captcha = Request::post('captcha');
            }
    
            // stop registration flow if registrationInputValidation() returns false (= anything breaks the input check rules)
            $validation_result = self::registrationInputValidation($captcha, $user_name, $user_password_new, $user_password_repeat, $user_email);
            if (!$validation_result) {
                return false;
            }

    Don't overlook this minor change in the above code
    from

    $validation_result = self::registrationInputValidation(Request::post('captcha').....

    to

    $validation_result = self::registrationInputValidation($captcha......

    Hope this helps :)

  22. panique commented on Oct 11, 2015

    @panique
    Owner

    Hey, this is linked from the readme now, but I think it's better to simply leave this as a ticket instead of implementing it by default (as this would become tricky with the additional composer-dependency that wouldn't be needed by 90% of the users)... hmm... hard decision...

    Anyway, users who read the readme will find this :)

  23. christiangrieger commented on Jan 10, 2016

    @christiangrieger

    Looks like the code base got a bit changed? Would you be so friendly to explain exactly how i can add recaptcha to the register page? :) (So what exactly i have to replace) Thank you very much.

    I created the values on config changed the registration page added the captcha model but when i try to register and click the captcha it tells me its wrong if i let the captcha empty i can register without it .. :(

  24. DonSYS91 commented on Nov 6, 2017

    @DonSYS91

    Along with those changes I have fork a copy and implemented reCAPTCHA:
    https://github.com/donmccoy/huge

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions