Captcha Verification in forms Using PHP

Captcha Verification

Why Captcha verification is required?

Captcha Verification is used to prevent automated programs submitting spam or unwanted contents. It is used to verify the data is entered by human or bots and prevent the bots content. So we can avoid spam data’s.

Captcha Verification

Steps Invloved in Captcha verification:

Captcha works in live domains only, it won’t work in local host, we can add more than one domains for creating site key and secret key.

There are 3 main and easy steps involved in captcha verification, which are listed below,

  1. Create site key and secret key from https://www.google.com/recaptcha link.
  2. Now we have to include that captcha field in form.
  3. Server side Validation of that captcha and submitting details.

Site key is used for displaying captcha in front end,secret key is used for validation of captcha at server side.

How to include captcha in form:

<div class="col-md-6 col-sm-6 col-xs-12">
<div class="g-recaptcha"data-sitekey="6Lft23kUAAAAAFlpwYZle9ZjF4GaJRlRMF93m7L3"></div>
</div>

In this site key use your site key generated at step1.and include below mentioned script file, for the visibility of the captcha.

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

Now u can see that captcha is included in your form, now u have to validate that captcha and need to submit the form,

Validation and Submitting Details:

Upto my knowledge, server side validation only used for Google captcha verifications,here,i suggested server side validation for captcha as mentioned below,

Here we have to use that secret key for server validation.

First we have to confirm captcha verification,whether captcha is checked or not,and images selected correct or not.

g-recaptcha-response is the captcha response sent by GET or POST method,here am using post method.

First if we did’t get get g-recaptcha-response it goes to else part and throws the validation error.

Once we get the response it goes inside the condition and checks the accuracy of entered captacha,using api and inbuilt functions google captcha,

if the captcha is verified successfully,we can get the other details via post method and after validation we can send a mail to the mentioned user using php mail() function or SMTP method.

if(isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']))
{
$captcha=$_POST['g-recaptcha-response'];
if(!$captcha)
{
 $msg    = ‘’;
}
 else
{
  $secretKey = "6Lft23kUAAAAAG8JraxzPUea1C2KSmAo2nH-Hm4w";
  $ip = $_SERVER['REMOTE_ADDR'];
  $ch = curl_init();
  curl_setopt($ch,CURLOPT_URL,"https://www.google.com/recaptcha/api/siteverify");
  curl_setopt($ch,CURLOPT_POST, 1);
  curl_setopt($ch,CURLOPT_POSTFIELDS,"secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  $err = curl_error($ch);
  curl_close($ch);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) == 1)
{
  //here u can get the details of form and send to mentioned mail id.
}
  else
{
  echo "<script>alert('Please Enter valid details');window.location='contact.html';</script>";
}
}
  else
{
  echo "<script>alert('Please Enter Valid Captacha');window.location='contact.html';</script>";
}
}
}
 else
{
 echo "<script>alert('Please verify captcha'); window.location='contact.html';</script>";
}

How to handle Exception in PHP

Earlier versions of PHP version did not have a method to handle “No Exception Handle”. PHP 5.0 and above today supports this function by using catch blocks for errors and exception handling.

Some Basics about Exception: 

1-PHP throw and PHP catch:

      This method will work by default by using PHP try catch. The program execution will stop and display an error message that the programmer can easily understand.

2-PHP throw and our catch:

How try-catch block works are explained below. When PHP throws exception (eg. divide any number with 0) we will catch that exception after the try block. In PHP we have limited exception list. If the programmer desired to customize exception that option is available below. But Important thing after exception our program will not end.

3-OUR throw and PHP catch:

    If We just throw error and PHP will catch the exception. We can customize the exception but after the exception, our program execution will stop and display an error message. This is not an advisable method.

4-OUR throw and our catch:

        We can throw and catch any type of exception. This Method is used across all programming languages. We can also customize error message and exception. In this method, program execution will not stop after exception, display error message and execute after catch block code.

Note: If we are not using catch block then after exception definitely our program will stop and display programmer understandable error message.  

Try, Catch, Finally, Throw:-

try {
// start code to run here
}
catch (Exception $ex) {
echo $ex->getMessage(); //First Catch block
}
catch (InvalidArgumentException $ex) {
echo $ex->getMessage(); //Second Catch block
}
finally {
// finally block is optional
}

Try:

This block contains all who have come exception on executed time. If exception comes then this block will stop to execute.

Throw:

In the Throw keyword, we used occurrence exception in PHP and use try, catch in runtime.

Catch:

The Catch block we pass exception type and write to handle code inside the catch block.

Finally:

This Finally blocks come in PHP version 5.5 This block we have to write special Syntex. Finally, create a block of code that will be executed after a try(if catch not available) or catch block has completed and before the code following the try or catch block. Finally, the block will execute if no catch statement matches the exception.

How to handle multiple type exception in PHP:-

After PHP version 5.5 we can write multiple catch blocks in one try. PHP allows customizing code according to the type of exception. We can also customize the error code also.

try {
// start code to run here
}
catch (Exception $ex) {
echo $ex->getMessage(); //First Catch block
}
catch (InvalidArgumentException $ex) {
echo $ex->getMessage(); //Second Catch block
}
finally {
// finally block is optional
}

In PHP Exception handling provides a powerful mechanism for controlling complex programs that have many dynamic run-time characteristics.

A try and is catch statement form a unit. The statement that is protected by try must be use {}. You can not use try on a single statement.

Creating our type PHP Exception:-

PHP we can create our type exception. This is very useful for any application that you can have special exception handling around. In our program we create functions for exception occur than execute. The class (DivideByNegativeException) should be an extension of the exception class.

class DivideByNegativeException extends Exception {};

class DivideByZeroException extends Exception {};function divide_process($denominator)
{
try
{
if ($denominator < 0)
{
throw new DivideByNegativeException();
}
else if ($denominator == 0)
{
throw new DivideByZeroException();
}
else
{
echo 25 / $denominator;
}
}
catch (DivideByZeroException $e)
{
echo “This program has Divided by zero exception!”;
}catch (DivideByNegativeException $e)
{
echo “This program Divide by negative number exception!”;
}catch (Exception $e)
{
echo “This program have UNKNOWN EXCEPTION!”;
}
}

This code have custom type exception class. The DivideByNegativeException() and DivideByZeroException() classes are created as extensions of the existing Exception class; this way, it inherit all method and properties from the Exception class. Try block is executed and exception is thrown if denominator is negative or zero number. The catch block catch the exception and display the error message.

Nested try Statement:

       In PHP try statement can be nested, It means inside try statement we can use one or more try statement. Every time try statement pushed exception and we use one or multiple catch block outside  main try block. If any exception come in any try block then all try block  execution stop and our program automatic redirect to catch block if exception handle propery then error message display and program not end  otherwise program excecution stop.

We can also configure global PHP exception handler, we will use the set_exception_handler() function to set a user-defined function to handle all uncaught exceptions.

function global_exception_handler($exception)
{
echo “This program Exception:” . $exception->getMessage();
}
set_exception_handler(‘global_exception_handler’);