Rectangle 27 70

There are a few great examples:

thanks for quick reply. I have a question, who created Recaptcha.dll? Google team?

I'm using Dirik Whittaker's code. Microsoft.Web.Helpers is referenced, but I'm getting a namespace name 'Recaptcha' not found error on this line: var captchaValidtor = new Recaptcha.RecaptchaValidator

@M3NTA7 You may want to pose a question that goes into a bit more depth than this comment.

c# - How to implement reCaptcha for ASP.NET MVC? - Stack Overflow

c# asp.net asp.net-mvc-2
Rectangle 27 27

I have added reCaptcha to a project I'm currently working on. I needed it to use the AJAX API as the reCaptcha element was loaded into the page dynamically. I couldn't find any existing controls and the API is simple so I created my own.

1: Add the script tag to the master page headers

<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>

2: Add your keys to the web.config

<appSettings>
    <add key="ReCaptcha.PrivateKey" value="[key here]" />
    <add key="ReCaptcha.PublicKey" value="[key here]" />
</appSettings>

3: Create the Action Attribute and Html Helper extensions

namespace [Your chosen namespace].ReCaptcha
{
    public enum Theme { Red, White, BlackGlass, Clean }

    [Serializable]
    public class InvalidKeyException : ApplicationException
    {
        public InvalidKeyException() { }
        public InvalidKeyException(string message) : base(message) { }
        public InvalidKeyException(string message, Exception inner) : base(message, inner) { }
    }

    public class ReCaptchaAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var userIP = filterContext.RequestContext.HttpContext.Request.UserHostAddress;

            var privateKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PrivateKey", "");

            if (string.IsNullOrWhiteSpace(privateKey))
                throw new InvalidKeyException("ReCaptcha.PrivateKey missing from appSettings");

            var postData = string.Format("&privatekey={0}&remoteip={1}&challenge={2}&response={3}",
                                         privateKey,
                                         userIP,
                                         filterContext.RequestContext.HttpContext.Request.Form["recaptcha_challenge_field"],
                                         filterContext.RequestContext.HttpContext.Request.Form["recaptcha_response_field"]);

            var postDataAsBytes = Encoding.UTF8.GetBytes(postData);

            // Create web request
            var request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            request.ContentLength = postDataAsBytes.Length;
            var dataStream = request.GetRequestStream();
            dataStream.Write(postDataAsBytes, 0, postDataAsBytes.Length);
            dataStream.Close();

            // Get the response.
            var response = request.GetResponse();

            using (dataStream = response.GetResponseStream())
            {
                using (var reader = new StreamReader(dataStream))
                {
                    var responseFromServer = reader.ReadToEnd();

                    if (!responseFromServer.StartsWith("true"))
                        ((Controller)filterContext.Controller).ModelState.AddModelError("ReCaptcha", "Captcha words typed incorrectly");
                }
            }
        }
    }

    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString GenerateCaptcha(this HtmlHelper helper, Theme theme, string callBack = null)
        {
            const string htmlInjectString = @"<div id=""recaptcha_div""></div>
<script type=""text/javascript"">
    Recaptcha.create(""{0}"", ""recaptcha_div"", {{ theme: ""{1}"" {2}}});
</script>";

            var publicKey = ConfigurationManager.AppSettings.GetString("ReCaptcha.PublicKey", "");

            if (string.IsNullOrWhiteSpace(publicKey))
                throw new InvalidKeyException("ReCaptcha.PublicKey missing from appSettings");

            if (!string.IsNullOrWhiteSpace(callBack))
                callBack = string.Concat(", callback: ", callBack);

            var html = string.Format(htmlInjectString, publicKey, theme.ToString().ToLower(), callBack);
            return MvcHtmlString.Create(html);
        }
    }
}

4: Add the captcha to your view

@using (Html.BeginForm("MyAction", "MyController"))
{
   @Html.TextBox("EmailAddress", Model.EmailAddress)
   @Html.GenerateCaptcha(Theme.White)
   <input type="submit" value="Submit" />
}

5: Add the attribute to your action

[HttpPost]
[ReCaptcha]
public ActionResult MyAction(MyModel model)
{
   if (!ModelState.IsValid) // Will have a Model Error "ReCaptcha" if the user input is incorrect
      return Json(new { capthcaInvalid = true });

   ... other stuff ...
}

6: Note you will need to reload the captcha after each post even if it was valid and another part of the form was invalid. Use Recaptcha.reload();

If you are implementing this solution have into account that the new API url is: google.com/recaptcha/api/siteverify (source)

c# - How to implement reCaptcha for ASP.NET MVC? - Stack Overflow

c# asp.net asp.net-mvc-2
Rectangle 27 6

Simple and Complete Solution working for me. Supports ASP.NET MVC 4 and 5 (Supports ASP.NET 4.0, 4.5, and 4.5.1)

Step 2: Add your Public and Private key to your web.config file in appsettings section

<appSettings>
    <add key="ReCaptchaPrivateKey" value=" -- PRIVATE_KEY -- " />
    <add key="ReCaptchaPublicKey" value=" -- PUBLIC KEY -- " />
</appSettings>

You can create an API key pair for your site at https://www.google.com/recaptcha/intro/index.html and click on Get reCAPTCHA at top of the page

@using reCAPTCHA.MVC
@using (Html.BeginForm())
{
    @Html.Recaptcha()
    @Html.ValidationMessage("ReCaptcha")
    <input type="submit" value="Register" />
}

Step 4: Implement the Controller Action that will handle the form submission and Captcha validation

[CaptchaValidator(
PrivateKey = "your private reCaptcha Google Key",
ErrorMessage = "Invalid input captcha.",
RequiredMessage = "The captcha field is required.")]
public ActionResult MyAction(myVM model)
{
    if (ModelState.IsValid) //this will take care of captcha
    {
    }
}
public ActionResult MyAction(myVM model, bool captchaValid)
{
    if (captchaValid) //manually check for captchaValid 
    {
    }
}
Uncaught Error: ReCAPTCHA placeholder element must be empty

c# - How to implement reCaptcha for ASP.NET MVC? - Stack Overflow

c# asp.net asp.net-mvc-2
Rectangle 27 57

Unless I'm missing something, what's wrong with using reCAPTCHA as all the work is done externally.

Just a thought.

Re-captcha is user-hostile. Captchs is bad enough. But making it harder for users in order to get some tiny OCR benefit is positively hostile.

It's user-hostile because sometimes the images are hard to decode even for humans, and may cause frustration in legitimate users when this happens. See Josh's link with worst CAPTCHAS for some examples of overly hard to decode images.

@Andrei you can always make reCAPTCHA load another image if it is too hard for you.

reCAPTCHA is fine, and it implements an accessibility option which 95% of homegrown solutions don't even think about.

security - Practical non-image based CAPTCHA approaches? - Stack Overf...

security language-agnostic captcha
Rectangle 27 57

Unless I'm missing something, what's wrong with using reCAPTCHA as all the work is done externally.

Just a thought.

Re-captcha is user-hostile. Captchs is bad enough. But making it harder for users in order to get some tiny OCR benefit is positively hostile.

It's user-hostile because sometimes the images are hard to decode even for humans, and may cause frustration in legitimate users when this happens. See Josh's link with worst CAPTCHAS for some examples of overly hard to decode images.

@Andrei you can always make reCAPTCHA load another image if it is too hard for you.

reCAPTCHA is fine, and it implements an accessibility option which 95% of homegrown solutions don't even think about.

security - Practical non-image based CAPTCHA approaches? - Stack Overf...

security language-agnostic captcha
Rectangle 27 57

Unless I'm missing something, what's wrong with using reCAPTCHA as all the work is done externally.

Just a thought.

Re-captcha is user-hostile. Captchs is bad enough. But making it harder for users in order to get some tiny OCR benefit is positively hostile.

It's user-hostile because sometimes the images are hard to decode even for humans, and may cause frustration in legitimate users when this happens. See Josh's link with worst CAPTCHAS for some examples of overly hard to decode images.

@Andrei you can always make reCAPTCHA load another image if it is too hard for you.

reCAPTCHA is fine, and it implements an accessibility option which 95% of homegrown solutions don't even think about.

security - Practical non-image based CAPTCHA approaches? - Stack Overf...

security language-agnostic captcha
Rectangle 27 1

An async version for MVC 5 (i.e. avoiding ActionFilterAttribute, which is not async until MVC 6) and reCAPTCHA 2

public class HomeController : Controller
{
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> ContactSubmit(
        [Bind(Include = "FromName, FromEmail, FromPhone, Message, ContactId")]
        ContactViewModel model)
    {
        if (!await RecaptchaServices.Validate(Request))
        {
            ModelState.AddModelError(string.Empty, "You have not confirmed that you are not a robot");
        }
        if (ModelState.IsValid)
        {
           ...
@model MyMvcApp.Models.ContactViewModel

@*This is assuming the master layout places the styles section within the head tags*@
@section Styles {
    @Styles.Render("~/Content/ContactPage.css")
    <script src='https://www.google.com/recaptcha/api.js'></script>
}

@using (Html.BeginForm("ContactSubmit", "Home",FormMethod.Post, new { id = "contact-form" }))
{
    @Html.AntiForgeryToken()
    ...
    <div class="form-group">
      @Html.LabelFor(m => m.Message) 
      @Html.TextAreaFor(m => m.Message, new { @class = "form-control", @cols = "40", @rows = "3" })
      @Html.ValidationMessageFor(m => m.Message)
    </div>

    <div class="row">
      <div class="g-recaptcha" data-sitekey='@System.Configuration.ConfigurationManager.AppSettings["RecaptchaClientKey"]'></div>
    </div>

    <div class="row">
      <input type="submit" id="submit-button" class="btn btn-default" value="Send Your Message" />
    </div>
}
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Web;
using System.Configuration;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Runtime.Serialization;

namespace MyMvcApp.Services
{
    public class RecaptchaServices
    {
        //ActionFilterAttribute has no async for MVC 5 therefore not using as an actionfilter attribute - needs revisiting in MVC 6
        internal static async Task<bool> Validate(HttpRequestBase request)
        {
            string recaptchaResponse = request.Form["g-recaptcha-response"];
            if (string.IsNullOrEmpty(recaptchaResponse))
            {
                return false;
            }
            using (var client = new HttpClient { BaseAddress = new Uri("https://www.google.com") })
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("secret", ConfigurationManager.AppSettings["RecaptchaSecret"]),
                    new KeyValuePair<string, string>("response", recaptchaResponse),
                    new KeyValuePair<string, string>("remoteip", request.UserHostAddress)
                });
                var result = await client.PostAsync("/recaptcha/api/siteverify", content);
                result.EnsureSuccessStatusCode();
                string jsonString = await result.Content.ReadAsStringAsync();
                var response = JsonConvert.DeserializeObject<RecaptchaResponse>(jsonString);
                return response.Success;
            }
        }

        [DataContract]
        internal class RecaptchaResponse
        {
            [DataMember(Name = "success")]
            public bool Success { get; set; }
            [DataMember(Name = "challenge_ts")]
            public DateTime ChallengeTimeStamp { get; set; }
            [DataMember(Name = "hostname")]
            public string Hostname { get; set; }
            [DataMember(Name = "error-codes")]
            public IEnumerable<string> ErrorCodes { get; set; }
        }

    }
}
<configuration>
  <appSettings>
    <!--recaptcha-->
    <add key="RecaptchaSecret" value="***secret key from https://developers.google.com/recaptcha***" />
    <add key="RecaptchaClientKey" value="***client key from https://developers.google.com/recaptcha***" />
  </appSettings>
</configuration>

c# - How to implement reCaptcha for ASP.NET MVC? - Stack Overflow

c# asp.net asp.net-mvc-2
Rectangle 27 3

Paste this snippet before the closing </head> tag on your HTML template:

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

Paste this snippet at the end of the <form> where you want the reCAPTCHA widget to appear:

<div class="g-recaptcha" data-sitekey="your-site-key"></div>

When your users submit the form where you integrated reCAPTCHA, you'll get as part of the payload a string with the name "g-recaptcha-response". In order to check whether Google has verified that user, send a POST request with these parameters:

response : The value of 'g-recaptcha-response'.

Now in action of your MVC app:

// return ActionResult if you want
    public string RecaptchaWork()
    {
        // Get recaptcha value
        var r = Request.Params["g-recaptcha-response"];
        // ... validate null or empty value if you want
        // then
        // make a request to recaptcha api
        using (var wc = new WebClient())
        {
            var validateString = string.Format(
                "https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}",
               "your_secret_key",    // secret recaptcha key
               r); // recaptcha value
             // Get result of recaptcha
            var recaptcha_result = wc.DownloadString(validateString);
            // Just check if request make by user or bot
            if (recaptcha_result.ToLower().Contains("false"))
            {
                 return "recaptcha false";
            }
        }
        // Do your work if request send from human :)
    }

c# - How to implement reCaptcha for ASP.NET MVC? - Stack Overflow

c# asp.net asp.net-mvc-2
Rectangle 27 206

"If you would like to use "localhost" for development, you must add it to the list of domains."

This will only work if you access localhost using 127.0.0.1/... rather than localhost/....

"By default, all keys work on "localhost" (or "127.0.0.1"), so you can always develop and test on your local machine."

In other words, simply use the same key.

I checked to confirm whether the words were on that page. It was gone! In 2015, you can find the above quote @ developers.google.com/recaptcha/docs/start

This answer is accurate, but there's an important caveat that stumped me: When migrating from reCAPTCHA v1 to v2, it is necessary to regenerate the API keys in order for this message to disappear. Further, and equally important, if you're like me and you setup test domains in your local/development environment by placing entries into the operating system's "hosts" file, you will need to add those "fake" domains to the allowed domains for the reCAPTCHA account in question to resolve the "ERROR: Invalid domain for site key" error.

When your localhost isn't named "localhost" then it's not working.

while localhost did not work for me I was able to use both 127.0.0.1 and also a *.xip.io address.

Using reCAPTCHA on localhost - Stack Overflow

localhost recaptcha
Rectangle 27 3

How about using reCAPTCHA? It has plugins that are easy to use (PHP for example).

Actually even though everybody has great explinations and suggestions I went with this option. This way I'm not trusting some random Wordpress Captcha plugin I'm putting my trust in google to keep spam out. We'll see how this works. Thanks.

php - Spam Defeating All My Captcha - Stack Overflow

php wordpress captcha recaptcha spam
Rectangle 27 22

  • Add localhost & 127.0.0.1 to domains of a new site like the following image.

If your question is how to set reCaptcha in Google site for using it in localhost, then i has been wrote it above but if you are curious that how you can using reCAPTCHA on both localhost and website host by minimal codes in your controller and prevent some codes like ConfigurationManager.AppSettings["ReCaptcha:SiteKey"] in it then I help you with this extra description and codes in my answer.

Do you like the following GET and POST actions?

[HttpGet]
[Recaptcha]
public ActionResult Register()
{
    // Your codes in GET action
}

[HttpPost]
[Recaptcha]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model, string reCaptcha_SecretKey){
   // Your codes in POST action
   if (!ModelState.IsValid || !ReCaptcha.Validate(reCaptcha_SecretKey))
   {
       // Your codes
   }
   // Your codes
}
@ReCaptcha.GetHtml(@ViewBag.publicKey)

@if (ViewBag.RecaptchaLastErrors != null)
{
    <div>Oops! Invalid reCAPTCHA =(</div>
}

A) Add the following ActionFilter to your Web project:

public class RecaptchaAttribute : FilterAttribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var setting_Key = filterContext.HttpContext.Request.IsLocal ? "ReCaptcha_Local" : "ReCaptcha";
        filterContext.ActionParameters["ReCaptcha_SecretKey"] = ConfigurationManager.AppSettings[$"{setting_Key}:SecretKey"];
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var setting_Key = filterContext.HttpContext.Request.IsLocal ? "ReCaptcha_Local" : "ReCaptcha";
        filterContext.Controller.ViewBag.Recaptcha = ReCaptcha.GetHtml(publicKey: ConfigurationManager.AppSettings[$"{setting_Key}:SiteKey"]);
        filterContext.Controller.ViewBag.publicKey = ConfigurationManager.AppSettings[$"{setting_Key}:SiteKey"];
    }
}

B) Add the reCaptcha settings keys for both localhost & website like it in your webconfig file:

<appSettings>

    <!-- RECAPTCHA SETTING KEYS FOR LOCALHOST -->
    <add key="ReCaptcha_Local:SiteKey" value="[Localhost SiteKey]" />
    <add key="ReCaptcha_Local:SecretKey" value="[Localhost SecretKey]" />
    <!-- RECAPTCHA SETTING KEYS FOR WEBSITE -->
    <!--<add key="ReCaptcha:SiteKey" value="[Webite SiteKey]" />
    <add key="ReCaptcha:SecretKey" value="[Webite SecretKey]" />-->

    <!-- OTHER SETTING KEYS OF YOUR PROJECT -->

</appSettings>

Note: By this way you did not need set reCaptcha_SecretKey parameter in the post action or any ViewBag for reCaptcha manually in your Actions and Views, all of them will be filled automatically at runtime with appropriate values depending on you have run the project on the localhost or website.

This should be the accepted answer.

Using reCAPTCHA on localhost - Stack Overflow

localhost recaptcha
Rectangle 27 29

Here's a version that uses the JavaScriptSerializer. Thanks Ala for the basis for this code.

WebConfig App Setting - I've added the secret key to the Web.Config in my case to allow transforms between environments. It can also be easily encrypted here if required.

<add key="Google.ReCaptcha.Secret" value="123456789012345678901234567890" />

The ReCaptcha Class - A simple class to post the response parameter along with your secret to Google and validate it. The response is deserialized using the .Net JavaScriptSerializer class and from that true or false returned.

using System.Collections.Generic;
using System.Configuration;

public class ReCaptcha
{   
    public bool Success { get; set; }
    public List<string> ErrorCodes { get; set; }

    public static bool Validate(string encodedResponse)
    {
        if (string.IsNullOrEmpty(encodedResponse)) return false;

        var client = new System.Net.WebClient();
        var secret = ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"];

        if (string.IsNullOrEmpty(secret)) return false;

        var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse));

        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        var reCaptcha = serializer.Deserialize<ReCaptcha>(googleReply);

        return reCaptcha.Success;
    }
}

Validate The Response - Check the validity of the g-Recaptcha-Response form parameter in your Controller (or code behind for a web form) and take appropriate action.

var encodedResponse = Request.Form["g-Recaptcha-Response"];
var isCaptchaValid = ReCaptcha.Validate(encodedResponse);

if (!isCaptchaValid)
{
    // E.g. Return to view or set an error message to visible
}

This seems to be a good solution for those interested in the simplest implementation, especially without using the Newtonsoft libraries.

c# - Validating Recaptcha 2 (No CAPTCHA reCAPTCHA) in ASP.NET's server...

c# asp.net vb.net recaptcha
Rectangle 27 29

Here's a version that uses the JavaScriptSerializer. Thanks Ala for the basis for this code.

WebConfig App Setting - I've added the secret key to the Web.Config in my case to allow transforms between environments. It can also be easily encrypted here if required.

<add key="Google.ReCaptcha.Secret" value="123456789012345678901234567890" />

The ReCaptcha Class - A simple class to post the response parameter along with your secret to Google and validate it. The response is deserialized using the .Net JavaScriptSerializer class and from that true or false returned.

using System.Collections.Generic;
using System.Configuration;

public class ReCaptcha
{   
    public bool Success { get; set; }
    public List<string> ErrorCodes { get; set; }

    public static bool Validate(string encodedResponse)
    {
        if (string.IsNullOrEmpty(encodedResponse)) return false;

        var client = new System.Net.WebClient();
        var secret = ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"];

        if (string.IsNullOrEmpty(secret)) return false;

        var googleReply = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secret, encodedResponse));

        var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

        var reCaptcha = serializer.Deserialize<ReCaptcha>(googleReply);

        return reCaptcha.Success;
    }
}

Validate The Response - Check the validity of the g-Recaptcha-Response form parameter in your Controller (or code behind for a web form) and take appropriate action.

var encodedResponse = Request.Form["g-Recaptcha-Response"];
var isCaptchaValid = ReCaptcha.Validate(encodedResponse);

if (!isCaptchaValid)
{
    // E.g. Return to view or set an error message to visible
}

This seems to be a good solution for those interested in the simplest implementation, especially without using the Newtonsoft libraries.

c# - Validating Recaptcha 2 (No CAPTCHA reCAPTCHA) in ASP.NET's server...

c# asp.net vb.net recaptcha
Rectangle 27 90

While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.

function isValid() 
{
    try {

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => '[YOUR SECRET KEY]',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];

        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];

        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}

Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).

Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }

$data = ...
$options = ...
$data = array('secret'   => '[YOUR SECRET KEY]',                  'response' => $_POST['g-recaptcha-response'],                  'remoteip' => $_SERVER['REMOTE_ADDR']);          $options = array(             'http' => array(                 'header'  => "Content-type: application/x-www-form-urlencoded\r\n",                 'method'  => 'POST',                 'content' => http_build_query($data)              )         );
if (empty($_POST['g-recaptcha-response'])) {   return false; }

https urls are actually encrypted, so the private key is not exposed even when using a GET request, see: stackoverflow.com/questions/499591/are-https-urls-encrypted

Please note, for debugging purposes, you can only call isValid() once. If called a second time, it will return false. Found this out the hard way with an echo statement...

Something like this should be in the official docs...

new google recaptcha with checkbox server side php - Stack Overflow

php recaptcha
Rectangle 27 90

While the answers here are definately working, they are using a GET request, which exposes your private key (even though https is used). On Google Developers the specified method is POST.

function isValid() 
{
    try {

        $url = 'https://www.google.com/recaptcha/api/siteverify';
        $data = ['secret'   => '[YOUR SECRET KEY]',
                 'response' => $_POST['g-recaptcha-response'],
                 'remoteip' => $_SERVER['REMOTE_ADDR']];

        $options = [
            'http' => [
                'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
                'method'  => 'POST',
                'content' => http_build_query($data) 
            ]
        ];

        $context  = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return json_decode($result)->success;
    }
    catch (Exception $e) {
        return null;
    }
}

Array Syntax: I use the "new" array syntax ( [ and ] instead of array(..) ). If your php version does not support this yet, you will have to edit those 3 array definitions accordingly (see comment).

Return Values: This function returns true if the user is valid, false if not, and null if an error occured. You can use it for example simply by writing if (isValid()) { ... }

$data = ...
$options = ...
$data = array('secret'   => '[YOUR SECRET KEY]',                  'response' => $_POST['g-recaptcha-response'],                  'remoteip' => $_SERVER['REMOTE_ADDR']);          $options = array(             'http' => array(                 'header'  => "Content-type: application/x-www-form-urlencoded\r\n",                 'method'  => 'POST',                 'content' => http_build_query($data)              )         );
if (empty($_POST['g-recaptcha-response'])) {   return false; }

https urls are actually encrypted, so the private key is not exposed even when using a GET request, see: stackoverflow.com/questions/499591/are-https-urls-encrypted

Please note, for debugging purposes, you can only call isValid() once. If called a second time, it will return false. Found this out the hard way with an echo statement...

Something like this should be in the official docs...

new google recaptcha with checkbox server side php - Stack Overflow

php recaptcha
Rectangle 27 30

I use the Google ReCaptcha and it works very well and is very simple to implement.

Note that if you are using Https be sure you have the current version of the dll (1.0.5.0 at this time)

You need to create an account on the Google Recaptcha site and get a set of public and private keys. Add the keys to your web project main web.config file:

<appSettings>
    <add key="webpages:Version" value="1.0.0.0"/>
    <add key="ClientValidationEnabled" value="true"/>
    <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
    <add key="ReCaptchaPrivateKey" value="put your private key value here" />
    <add key="ReCaptchaPublicKey" value="put your public key value here" />
</appSettings>

Now use NuGet and install the reCAPTCHA plugin for .NET

Then, go to your web.config file inside of your VIEWS folder. Add this line:

<namespaces>
  <add namespace="System.Web.Mvc" />
  <add namespace="System.Web.Mvc.Ajax" />
  <add namespace="System.Web.Mvc.Html" />
  <add namespace="System.Web.Routing" />
  <add namespace="Recaptcha"/>
</namespaces>

Then, in your view that you want to show the captcha, add the using statement at the top of your file

@using Recaptcha;
<div class="editor-label">
    Are you a human?
</div>
<div class="editor-field">
    @Html.Raw(Html.GenerateCaptcha("captcha", "clean"))
    @Html.ValidationMessage("captcha")
</div>
[HttpPost]
[RecaptchaControlMvc.CaptchaValidator]
public ActionResult ForgotPassword(CheckUsernameViewModel model, bool captchaValid, string captchaErrorMessage) {
    if (!Membership.EnablePasswordReset)
        throw new Exception("Password reset is not allowed\r\n");
    if(ModelState.IsValid) {
        if(captchaValid) {
            return RedirectToAction("AnswerSecurityQuestion", new { username = model.Username });
        }
        ModelState.AddModelError("", captchaErrorMessage);
    }
    return View(model);
}

Following those steps have allowed me to implement captcha on several pages and it works smoothly. Note that the parameter names on the controller action MUST BE NAMED CORRECTLY:

bool captchaValid, string captchaErrorMessage

If you changed these parameter names you WILL get an error at runtime when your form posts back to the controller action.

What is the public/private key value? What should I put there?

@updev - you get that by signing up for them on Google's ReCaptcha page: google.com/recaptcha

@cd-smith: I got a strange behavior when following your guidelines to add Recaptcha to a MVC4 project ; the controller action get called twice when I submit the form, first with the correct Recaptcha results, and then a second time with error results! Did you face anything similar?

@ThomasWeiss No, I'm sorry I never had anything like that happen. But it sounds like a familiar situation. Are you posting via Ajax?

@cd-smith Thanks for your reply. No it's not Ajax so it's not a bind/unbind issue. And it only happens once the RecaptchaControlMvc.CaptchaValidator attribute is applied to the action... I'll have a deeper look with Fiddler to see if the second call to the action actually comes from the browser or is something internal. Will let you know!

asp.net - How to implement Google reCaptcha in an MVC3 application? - ...

asp.net asp.net-mvc asp.net-mvc-3 c#-4.0 recaptcha
Rectangle 27 7

public bool CheckCaptcha(string captchaResponse, string ipAddress)
{
    using (var client = new WebClient())
    {
        var response = client.DownloadString($"https://www.google.com/recaptcha/api/siteverify?secret={ ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"] }&response={ captchaResponse }&remoteIp={ ipAddress }");
        return JsonConvert.DeserializeObject<RecaptchaResponse>(response).Success;
    }
}

private class RecaptchaResponse
{
    [JsonProperty("success")]
    public bool Success { get; set; }
}

c# - Validating Recaptcha 2 (No CAPTCHA reCAPTCHA) in ASP.NET's server...

c# asp.net vb.net recaptcha
Rectangle 27 7

public bool CheckCaptcha(string captchaResponse, string ipAddress)
{
    using (var client = new WebClient())
    {
        var response = client.DownloadString($"https://www.google.com/recaptcha/api/siteverify?secret={ ConfigurationManager.AppSettings["Google.ReCaptcha.Secret"] }&response={ captchaResponse }&remoteIp={ ipAddress }");
        return JsonConvert.DeserializeObject<RecaptchaResponse>(response).Success;
    }
}

private class RecaptchaResponse
{
    [JsonProperty("success")]
    public bool Success { get; set; }
}

c# - Validating Recaptcha 2 (No CAPTCHA reCAPTCHA) in ASP.NET's server...

c# asp.net vb.net recaptcha
Rectangle 27 1

I would recommend you to use Google reCAPTCHA, is the best and easy to implement plus it comes with the trust of Google.

Very very effective and easy to implement.

ASP.NET MVC CAPTCHA implementation - Stack Overflow

asp.net asp.net-mvc asp.net-mvc-4 captcha
Rectangle 27 14

If you're looking for a fully customizable general solution which will even work with multiple forms on the same page, I'll explicitly render the reCaptcha widget by using the render=explicit and onload=aFunctionCallback parameters.

Here is a simple example:

<!DOCTYPE html>
<html>
<body>

<form action="" method="post">
    <input type="text" name="first-name-1"> <br />
    <input type="text" name="last-name-1"> <br />

    <div class="recaptcha-holder"></div>

    <input type="submit" value="Submit">
</form>

<br /><br />

<form action="" method="post">
    <input type="text" name="first-name-2"> <br />
    <input type="text" name="last-name-2"> <br />

    <div class="recaptcha-holder"></div>

    <input type="submit" value="Submit">
</form>

<script type="text/javascript">

  var renderGoogleInvisibleRecaptcha = function() {
    for (var i = 0; i < document.forms.length; ++i) {
      var form = document.forms[i];
      var holder = form.querySelector('.recaptcha-holder');
      if (null === holder){
        continue;
      }

      (function(frm){

        var holderId = grecaptcha.render(holder,{
          'sitekey': 'CHANGE_ME_WITH_YOUR_SITE_KEY',
          'size': 'invisible',
          'badge' : 'bottomright', // possible values: bottomright, bottomleft, inline
          'callback' : function (recaptchaToken) {
            HTMLFormElement.prototype.submit.call(frm);
          }
        });

        frm.onsubmit = function (evt){
          evt.preventDefault();
          grecaptcha.execute(holderId);
        };

      })(form);
    }
  };


</script>

<script src="https://www.google.com/recaptcha/api.js?onload=renderGoogleInvisibleRecaptcha&render=explicit" async defer></script>

</body>
</html>

As you can see, I am adding an empty div element into a form. In order to identify which forms should be protected using reCaptcha, I'll add a class name to this element. In our example I am using 'recaptcha-holder' class name.

The callback function iterates through all the existing forms and if it finds our injected element with the 'recaptcha-holder' class name, it will render the reCaptcha widget.

I've been using this solution on my Invisible reCaptcha for WordPress plugin. If somebody wants to see how this works, the plugin is available for download on WordPress directory:

Thanks, I'll look into this soon. I did actually get an issue with my registration page that contained both the login form (in the menu) and the registration one. Hopefully this might solve that issue!

Unlike Google's documentation, this was a helpful-ish starting point. However, I recommend one suggested change to anyone finding this in the future: Use frm.addEventListener('submit', function(evt) { ... }); instead of frm.onsubmit. I used a similar but more flexible approach in my FlexForms reCAPTCHA module (github.com/cubiclesoft/php-flexforms-modules).

Wait a moment. Where is the server side part?

Thank you for the example. I have implemented it on my test site, it works, but asks for challenge each time I click submit. This doesnt happen with your WordPress plugin. What is the problem with html example?

php - Implement the new Invisible reCaptcha from Google - Stack Overfl...

php html recaptcha