Laravel Google reCaptcha without package
Last Updated :
31 Jul, 2024
Captcha validation is extremely vital for safeguarding kind submission from the sender. It helps us to protect specious kind submissions to our website by bots. There are several captcha solutions for reducing spam kind submission. Out of these, the Google reCaptcha is safer, reliable, and most important is it's free. If you are looking for how to add Google reCaptcha in your website then this article is useful for you. In this article, we learn about, using laravel framework how to add Google reCaptcha without adding external package installation.
Steps to laravel Google reCaptcha validation: Below is the few steps following which we can use Google reCaptcha without package:
- Create a custom validation rule
- Create Recaptcha class
- Generate site key and secret key
- Update.env file in your project
- Create view file
- Google reCaptcha validation
1. Create a custom validation rule: By default, the laravel has many more rules of validation, but there is no rule for Google reCaptcha validation. But using one command we can make a simple custom validation rule for Google reCaptcha. By using the below command we make our custom validation rule
php artisan make:rule Recaptcha
2. Create Recaptcha class: After successful execution of this command, the reCaptcha class will be created in the path app/Rules directory. Then write the below code in the reCaptcha class file. The important thing is this code can be reused in your next project.
PHP
<? php
namespace App\Rules;
use Illuminate\Contracts\Validation\Rule;
class Recaptcha implements Rule {
public function __construct() {
}
public function passes($attribute, $value) {
$data = array('secret' => env('GOOGLE_RECAPTCHA_SECRET'),
'response' => $value);
try {
$verify = curl_init();
curl_setopt($verify, CURLOPT_URL,
"https://www.google.com/recaptcha/api/siteverify");
curl_setopt($verify, CURLOPT_POST, true);
curl_setopt($verify, CURLOPT_POSTFIELDS,
http_build_query($data));
curl_setopt($verify, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($verify, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($verify);
return json_decode($response) -> success;
}
catch (\Exception $e) {
return false;
}
}
public function message() {
return 'ReCaptcha verification failed.';
}
}
?>
3. Generate site key and secret key: Click on Google recapture you will get one page-like form, as shown in the picture below:
Google reCaptcha formBy adding your site and details you will get your website key and secret key. Save that key in your device notepad for further process.
4. Update .env file: Update the .env file of your project with a secret key and site key (Note: add your own site key and secret key, that is saved in your notepad).
GOOGLE_RECAPTCHA_KEY=<site key>
GOOGLE_RECAPTCHA_SECRET=<secret key>
5. Create a view file: Create a view or blade file to write the code where you want Google reCaptcha validation protection. You can use this code in any form that you want safely submit.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width,
initial-scale=1, shrink-to-fit=no">
<!-- CSS -->
<link rel="stylesheet" href=
"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://www.google.com/recaptcha/api.js"
async defer></script>
</head>
<body>
<div class="container mt-5">
<div class="card">
<div class="card-header text-center">
Google reCaptcha </div>
<div class="card-body">
<form action="validate-captcha.php"
method="post">
<div class="form-group">
<label for="exampleInputEmail1">
First Name</label>
<input type="text" name="name"
class="form-control" id="name"
required="">
</div>
<div class="form-group">
<label for="exampleInputEmail1">
Email </label>
<input type="email" name="email"
class="form-control" id="email"
aria-describedby="emailHelp"
required="">
</div>
<div class="form-group">
<label for="exampleInputEmail1">
Password</label>
<input type="password" name="password"
class="form-control" id="password"
required="">
</div>
<div class="form-group">
<label for="exampleInputEmail1">
Confirm Password</label>
<input type="password" name="cpassword"
class="form-control" id="cpassword"
required="">
</div>
<label>
<input type="checkbox" name="remember"
style="margin-bottom:15px">
I Accepts terms and conditions
</label>
<script src="https://www.google.com/recaptcha/api.js"
async defer></script>
<div class="g-recaptcha" id="feedback-recaptcha"
data-sitekey="{{ env('GOOGLE_RECAPTCHA_KEY') }}">
</div>
<input type="submit" name="password-reset-token"
class="btn btn-primary">
</form>
</div>
</div>
</div>
</body>
</html>
6. Google reCaptcha validation: In the final step, we add a custom validation rule at path app\Rules\GoogleRecaptcha. Add the below code to your file.
PHP
public function postContactForm(Request $request) {
$this -> validate($request, [
'g-recaptcha-response' =>
['required', new Recaptcha()]]);
// Recaptcha passed, do what ever you need
}
Output:
Similar Reads
How to remove a package from Laravel using PHP Composer?
Laravel is a famous PHP framework, and it uses Composer to handle packages. Adding packages to the Laravel project is something you often do, but sometimes you need to remove them to keep your project organized. In this article, you will learn the step-by-step process to remove a package from Larave
2 min read
Laravel | CSRF Protection
Cross-Site Request Forgery (CSRF) is a type of attack that performed by the attacker to send requests to a system with the help of an authorized user who is trusted by the system. Laravel provides protection with the CSRF attacks by generating a CSRF token. This CSRF token is generated automatically
3 min read
Google AMP amp-bind-recaptcha
The amp-bind allows elements to change the response to user inputs via data binding and simple JSON-like expressions and recaptcha element creates a recaptcha input using just amp-bind.Required Scripts: Importing amp-bind so that the recaptcha can have many states.HTML<script async custom-element
3 min read
How to download Google Images using Python
Python is a multi-purpose language and widely used for scripting. We can write Python scripts to automate day-to-day things. Letâs say we want to download google images with multiple search queries. Instead of doing it manually we can automate the process. How to install needed Module :Â pip install
2 min read
How to generate QR Codes with Angular 10 ?
QR Code (Quick Response Code) has become the essential component for each and every product, organization, app, etc. In marketing campaigns, we can use the generated QR code to Download appsSend EmailView business location etc. In this article let us see how to generate QR Codes with Angular 10. Pre
4 min read
How To Add Google Analytics in React?
Integrating Google Analytics into a React application enables you to monitor and analyze your websiteâs traffic and user behavior. This integration offers valuable insights into user interactions on your site, aiding in making informed decisions to enhance user experience and achieve business object
3 min read
Create a Radar Chart using Recharts in ReactJS
Radar charts, also known as spider or star charts, provide a powerful way to display data having multiple variable in a circular layout. Recharts is a popular charting library that is used for creating charts for React JS, provides an easy and efficient method to implement radar charts within your R
2 min read
Angular PrimeNG Captcha Component
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. It provides a lot of templates, components, theme design, an extensive icon library, and much more.
4 min read
How To Add Google Analytics To GitHub Pages
If you're hosting a website on GitHub Pages and want to track how many people visit your site and what they do there, Google Analytics is the perfect tool. It provides valuable insights that can help you understand your audience and improve your site.In this easy-to-follow guide, we'll show you how
4 min read
How to Verify Recaptcha in Node.js Server Call?
reCAPTCHA is a free service provided by Google that helps protect websites from spam and abuse by verifying that a user is human. Implementing and verifying reCAPTCHA in a Node.js server call involves a few steps, including obtaining a reCAPTCHA site key and secret key, integrating the reCAPTCHA wid
5 min read