Php

User Registration Form with PHP, MySQL and Google reCAPTCHA

Earlier, I have shared tutorial about Simple PHP Login System Using MySQL and jQuery AJAX. This tutorial is second part of user module to create user registration using php and MySQL with Google captcha. I am using Bootstrap to create registration form and jQuery validation plugin for form validation.We will do google PHP captcha validation from server side.

You can check other recommended tutorial of User Module in PHP,

I will use following files for this user Registration tutorial,

  • index.php : This file is main entry file of user management application.
  • response.php : This file will contain user registration method.
  • partials/ : This folder will have partial file like header.php and footer.php file.
  • connect/db_cls_connect.php : This folder will contain MySQL db connection file.
  • libs/ : This folder will have all dependencies files.

We need to create above files and folder structure into 'php_ajax_registraion_with_php_jquery' folder.

What’s Captcha

CAPTCHA stands for “Completely Automated Public Turing test to tell Computers and Humans Apart”, it’s a very common functionality to use at the time of submit data to prevent machines access of your website.

Create Signup table and MySQL Database Connection

We will create 'test' database into MySQL server and create 'tbl_users' table into this database using below SQL script,

--
-- Table structure for table `tbl_users`
--

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `id` int(11) NOT NULL,
  `user` varchar(255) DEFAULT NULL,
  `password` varchar(100) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `profile_photo` varchar(200) DEFAULT NULL,
  `active` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Let’s create a db_cls_connect.php file into connect folder if you did not created yet, We will add below MySQL connection information to connection php with MySQL.

<?php
session_start();
Class dbObj{
 /* Database connection start */ var $servername = "localhost";
 var $username = "root";
 var $password = "";
 var $dbname = "test";
 var $conn;
 function getConnstring() {
  $con = mysqli_connect($this--->servername, $this->username, $this->password, $this->dbname) or die("Connection failed: " . mysqli_connect_error());

  /* check connection */  if (mysqli_connect_errno()) {
   printf("Connect failed: %s\n", mysqli_connect_error());
   exit();
  } else {
   $this->conn = $con;
  }
  return $this->conn;
 }
}
?>

As you can see, I have passed below MySQL database parameters.

  • $servername : MySQL server host //localhost
  • $username : MySQL database user name //root
  • $password : MySQL database pass
  • $dbname : MySQL database name //test

How to use Google reCAPTCHA

It’s very easy to use and integrate with any application, The Google are providing well defined docs for each server side application, I am using PHP language, So I ll use php process to integrate google reCaptcha. You can download from PHP google reCaptcha Lib.

Register Hostname with Google reCAPTCHA

We are creating user registration form with captcha functionality. You can use or create custom captcha as well like Simple CAPTCHA Script Using PHP. To use Google reCAPTCHA, You need to register website hostname with google reCAPTCHA.

Google are providing Site key and Secret key against registered domain/website.You will use Site key and Secret key into your registration form to validate captcha form.There is also a js file that need to include into header of your application.

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

How to Display Google reCAPTCHA into HTML form

We will pass class name and data-sitekey site attribute with in captcha HTML container, The container may be HTML div, li span etc.

Related Post
 

PHP User Registration With MySQL and Google reCAPTCHA

Let’s create a user signup form using bootstrap 3 and added some jquery code to submit HTML form using ajax.The jQuery ajax submitted form values at server side using php.

We will do google captcha validation here and send exception message if validation failed, After successfully validating form values, We will save user information into HTML table.

Step 1: I am assuming you have already added bootstrap and jQuery lib files into index.php file,  if not added yes, please add into head section of index.php file otherwise add only google captcha js file.

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

Step 2: Create User Registration html view using bootstrap 3 and added below HTML code into register.php file.

 

I have defined a div(#error) which will use to show error message and '#success' div to show success message. I will use form id(#register-form) to validate input fields and button id for show sign-in process
at the end of form, I have added div to show google reCaptcha using data-sitekey attribute.

Step 3: Create submit register method into common.js file.

function registerForm() {  
  var data = $("#register-form").serialize();
  $.ajax({    
   type : 'POST',
   url  : 'response.php?action=register',
   data : data,
   beforeSend: function(){ 
    $("#error").fadeOut();
    $("#register_button").html('   sending ...');
   },
   success : function(response){
    console.log(response);
    if($.trim(response) === "1"){         
     $("#register_button").html('Signing In ...');
     $('#success').html('Successfully! User has been Registered.').show();
     setTimeout(' window.location.href = "index.php"; ',5000);
    } else {         
     $("#error").fadeIn(1000, function(){      
      $("#error").html(response).show();
     });
    }
   }
  });
  return false;
 }

registerForm() method will use into next step to validate form using jQuery validation, passed AJAX url 'response.php?action=register', so I need to create a method into response.php file to handle user register request and send response.

Step 4: We will use jquery form validation code into common.js file. We will add below code into this file.

$(document).ready(function(){
 /* handling form validation */ $("#register-form").validate({
  rules: {
   password: {
    required: true,
    minlength: 5,
   },
   re_password: {
    minlength: 5,
    equalTo : "#password",
   },
   f_name: {
    required: true,
   },
   l_name: {
    required: true,
   },
   email: {
    required: true,
    email: true
   },
  },
  messages: {
   password:"Please enter your password",
   email: "Please enter your email address",
   f_name: "Please enter your first name",
   l_name: "Please enter your last name",
  },
  submitHandler: registerForm 
 }); 

I have defined roles for each input fields and passed message on failed of validation, Since i am using jQuery so all validation process handle by client side. I have passed registerForm method to submitHandler once successfully validate all signup form fields.

Step 5: Created register method into response.php file.

//include connection file 
include_once("connect/db_cls_connect.php");
require('recaptcha/src/autoload.php');
$db = new dbObj();
$connString =  $db->getConnstring();

$params = $_REQUEST;
$action = $params['action'] !='' ? $params['action'] : '';
$empCls = new Employee($connString);

switch($action) {
 case 'register':
 $empCls->register();
 break;
 default:
 return;
 class Employee {
 protected $conn;
 protected $data = array();
 function __construct($connString) {
  $this->conn = $connString;
 }
 
 function register() {
  if(isset($_POST['register_button'])) {
   if (!isset($_POST['g-recaptcha-response'])) {
    throw new \Exception('ReCaptcha is not set.');
   }
   
   $recaptcha_secret_key = 'your secret key';
   $recaptcha = new \ReCaptcha\ReCaptcha($recaptcha_secret_key, new \ReCaptcha\RequestMethod\CurlPost());
   $response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
   if (!$response->isSuccess()) {
    throw new \Exception('ReCaptcha was not validated.');
   }
   
   $user_email = mysqli_real_escape_string($this->conn, trim($_POST['email']));
   $f_name = mysqli_real_escape_string($this->conn, trim($_POST['f_name']));
   $l_name = mysqli_real_escape_string($this->conn, trim($_POST['l_name']));
   $user_password = mysqli_real_escape_string($this->conn, trim($_POST['password']));
   $user_name= $f_name. ' '.$l_name;
   $sql = "INSERT INTO `tbl_users` (`user`, `password`, `email`, `profile_photo`, `active`) VALUES
     ('".$user_name."', '".$user_password."', '".$user_email."', NULL, 1);";
   $resultset = mysqli_query($this->conn, $sql) or die("database error:". mysqli_error($this->conn));
   //$row = mysqli_fetch_assoc($resultset);
   if($resultset){
    echo "1";
   } else {
    echo "Ohhh ! Something Wrong."; // wrong details
   }
  }
 }
}
}

We have added php google recaptcha into response.php file to access reCaptcha methods.We will first get all posted data from client side and passed to register method.We will check empty value and validate google recaptcha, after successful validation, we are saving user information into MySQL user table.

You can download source code and see Demo from below link.

View Comments

Recent Posts

Configure and Retrieve S3 Information Using Laravel PHP-AWS-SDK

This tutorial helps integrate a PHP SDK with Laravel. We'll install aws-php-sdk into laravel application and access all aws services… Read More

3 months ago

What is the Purpose of php_eol in PHP?

in this quick PHP tutorial, We'll discuss php_eol with examples. PHP_EOL is a predefined constant in PHP and represents an… Read More

9 months ago

Laravel Table Relationship Methods With Example

This Laravel tutorial helps to understand table Relationships using Elequonte ORM. We'll explore laravel table Relationships usage and best practices… Read More

9 months ago

Exploring the Power of Laravel Eloquent Join?

We'll explore different join methods of Laravel eloquent with examples. The join helps to fetch the data from multiple database… Read More

9 months ago

Quick and Easy Installation of Laravel Valet

in this Laravel tutorial, We'll explore valet, which is a development environment for macOS minimalists. It's a lightweight Laravel development… Read More

10 months ago

What is Laravel Soft Delete and How Does it Work?

I'll go through how to use soft delete in Laravel 10 in this post. The soft deletes are a method… Read More

10 months ago

Categories