PHP code example of phpninjas / recaptcha

1. Go to this page and download the library: Download phpninjas/recaptcha library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phpninjas / recaptcha example snippets



Google\ReCaptcha;

$recaptcha = new ReCaptcha($secret);
$resp = $recaptcha->validate($_POST['g-recaptcha-response']);

assert($resp->isSuccess());



 MyTest extends \PHPUnit_Framework_TestCase {

    public function testValidRecaptcha(){

        $goodResponse = [
          "success" => true
        ];

        $mockAdapter = $this->getMock('Google\HttpClientGetAdapter');
        $mockAdapter->expects($this->once())->method('get')->will($this->returnValue(json_encode($goodResponse)));

        $recaptcha = new ReCaptcha("secret", $mockAdapter);
        $this->assertThat($recaptcha->validate("my token thing"), $this->equalTo(new ReCaptchaResponse(true)));
    }

    public function testInvalidRecaptcha(){
        $badResponse = [
          "success" => false,
          "error-codes" => ["error1"]
        ];

        $mockAdapter = $this->getMock('Google\HttpClientGetAdapter');
        $mockAdapter->expects($this->once())->method('get')->will($this->returnValue(json_encode($badResponse)));

        $recaptcha = new ReCaptcha("secret", $mockAdapter);
        $this->assertThat($recaptcha->validate("my token thing"), $this->equalTo(new ReCaptchaResponse(false, ["error1"])));
    }
}


class MyHttpClient implements Google\HttpClientGetAdapter {
    public function get($uri){
        // do http magics here
        // fsockopen?
        // guzzle->get()
        // curl_exec()
        return $body
    }
}

$recaptcha = new ReCaptcha("secret", new MyHttpClient());
$recaptcha->validate("response token");


try {
    $recaptcha = new ReCaptcha("secret", new Guzzle());
    $recaptcha->validate("response token");
} catch(ReCaptchaException $e){
    // peek at the inner exception
    $e->getPrevious();
}

bash
curl -s https://getcomposer.org/installer | php
php composer.phar install