[RELEASE] PDO Registration Script with the new Google reCAPTCHA Verification

01/19/2016 21:39 treica#1
I have been asked by some people about how i built my Registration script with new [Only registered and activated users can see links. Click Here To Register...].

Well is not so hard to make this happen, in fact is a less of headache and is quite easy to implement...

DEMO (Style not included)

[Only registered and activated users can see links. Click Here To Register...]

So let's get started.

Requirements

- A Google account and retrieve a Public / Private key and put your website in the white list
- IIS / Apache web server
- PHP 5.4 or higher
- PDO installed
- SQLSRV driver installed

Installation

1. Create a new folder called reg / register (at your discretion as desired).
2. Inside reg folder create one more folder called libs.

3. Inside libs folder create a file named config.php and inside paste the below code

Code:
<?
//	Connect to MSSQL
	$sqlUser  = 'YOUR_USER';
	$sqlPass  = 'YOUR_PASS';
        $IP = 'YOUR_IP';
	$database = 'PS_UserData';

	try {
		$conn  = new PDO("sqlsrv:Server=$IP;Database=$database", $sqlUser, $sqlPass);
	}
	catch (PDOException $e){
    	die($e->getMessage());
	}
error_reporting(0);
?>
You need to edit the placeholders with your database details.

4. Now create a file named api.php still in libs folder and paste the following

Code:
<?
$ext = '.php';

include('config'.$ext);

if(isset($_POST) && !empty($_POST))
{
	$e = array();
	$ip = $_SERVER['REMOTE_ADDR'];
	$secretkey = "YOUR_GOOGLE_RECAPTCHA_PRIVATE_KEY";
    
    //check if isset Google reCAPTCHA
    if(isset($_POST['g-recaptcha-response'])){
        $captcha = $_POST['g-recaptcha-response'];
	}

        //initialize variables
	$success = false;
        $user = isset($_POST['Username']) ? trim($_POST['Username']) : '';
	$email = isset($_POST['Email']) ? trim($_POST['Email']) : '';
        $pw = isset($_POST['Password']) ? trim($_POST['Password']) : '';
        $rePw = isset($_POST['CPassword']) ? trim($_POST['CPassword']) : '';
	$response = json_decode(file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secretkey&response=$captcha&remoteip=$ip"),true);

        //check the username if exists
	$CheckUsername = $conn->prepare("SELECT Count(UserID) FROM dbo.Users_Master WHERE UserID = :Username");
	$CheckUsername->bindParam(':Username', $user, PDO::PARAM_STR);
	$CheckUsername->execute();
	$Number = $CheckUsername->fetchColumn();
	
        //check the email if exists
	$CheckEmail = $conn->prepare("SELECT Count(Email) FROM dbo.Users_Master WHERE Email = :Email");
	$CheckEmail->bindParam(':Email', $email, PDO::PARAM_STR);
	$CheckEmail->execute();
	$mailCheck = $CheckEmail->fetchColumn();
	

        //check the IP if exists if so, how many times? if there are 2 accounts we don't let to register another if($NumberIP[0] >= 1) should be edited to change
	$CheckIp = $conn->prepare("SELECT Count(UserUID) AS num_accs FROM Users_Master WHERE UserIp = :Ip");
	$CheckIp->bindParam(':Ip', $ip, PDO::PARAM_STR);
	$CheckIp->execute();
	$NumberIP = $CheckIp->fetch(PDO::FETCH_NUM);
		if($NumberIP[0] >= 1)
        {
            $e[] = "<h3>You already have an account registered!</h3>";
        }

	// Validate data
	if($Number > 0)
	{
		$e[] = "<h3>User name already exists, please choose a different user name.</h3>";
	}
	else if(empty($email))
	{
		$e[] = "<h3>Please provide an Email address</h3>";
	}
	else if($mailCheck > 0)
	{
		$e[] = "<h3>This Email address already exists</h3>";
	}
	else if(empty($pw))
	{
		$e[] = '<h3>Please provide a password.</h3>';
	}else if(strlen($pw) < 3 || strlen($pw) > 16)
	{
		$e[] = '<h3>Password must be between 3 and 16 characters in length.</h3>';
	}else if($pw != $rePw)
	{
		$e[] = '<h3>Passwords do not match.</h3>';
	}
	else if(empty($user) || empty($pw) || empty($rePw))
	{
		$e[] = "<h3>Required fields cannot be empty!</h3>";
	}
	else if($response['success'] == false)
	{
		$e[] = "<h3>Spam verification failed, please try again!</h3>";
	}
	else if(count($e) == 0)
	{
		$stmt = $conn->prepare("INSERT INTO Users_Master
				(UserID,Pw,JoinDate,Admin,AdminLevel,UseQueue,Status,Leave,LeaveDate,UserType,Point,EnPassword,UserIp,Email)
				VALUES (?,?,GETDATE(),0,0,0,0,0,GETDATE(),'N',0,'',?,?)");
		$params = array($user,$pw,$ip, $email);
		$stmt->execute($params);
		
		if($stmt == NULL)
		{
			$e[] = "<h3>API Failed, please contact an administrator!</h3>";
		}
		else
		{
			$success = htmlentities("<h3>Account {$user} successfully created!</h3>");
		}
	}
	// Determine which view to show.
if($success === false){
	require_once('../register.php');
}else{
	$success = htmlentities("Account {$user} successfully created!");
	echo "<center><b style=\"color:black\">".$success."</b></center>";
}
}
?>
Make sure to edit the line 10 with your Google reCAPTCHA private key.

5. Now let's go back to our reg / register folder and create a file named register.php this file will be the view our registration.

Code:
<!DOCTYPE html>
<html>
    <head>
    <title>Shaiya Registration</title>
    </head>
<body>
<!-- register form -->
<?php $e = array(); if(count($e) > 0){ ?>
			<ul id="error">
			<?php foreach($e as $error){ ?>
				<li><?php echo $error; ?></li>
			<?php } ?>
			</ul>
		<?php } ?>
<div style="width:50%">
<form method='post' action='/libs/api.php' id='createForm'>
    
                <ol>
                    <li>
                        <input type='Username' class='text createEmail validate' name='Username' id='Username' pattern='.{3,10}' maxlength='10' value="<?php if(isset($_POST['Username'])){ echo $_POST['Username']; } ?>" tabindex='1' placeholder="Username" required autofocus autocomplete='off' />
                    </li>
					<li>
					    <div class='passwordContainer'>
                        <input type='email' class='text createPassword validate' name='Email' id='Email' value="<?php if(isset($_POST['Email'])){ echo $_POST['Email']; } ?>" tabindex='1' placeholder="Your Email" required autocomplete='off' />
						<p>Use real email only!</p>
						</div>
                    </li>
                    <li>
                        <div class='passwordContainer'>
                            <input type='password' class='text createPassword validate' name='Password' id='Password' pattern='.{3,10}' tabindex='2' maxlength='10' value="<?php if(isset($_POST['Password'])){ echo $_POST['Password']; } ?>" placeholder="Your Password (max 10 char)" autocomplete='off' required />
                            <p>3 - 10 Characters | Letters or numbers only</p>
                        </div>
                    </li>
					<li>
                        <div class='passwordContainer'>
                            <input type='password' class='text createPassword validate' name='CPassword' id='CPassword' pattern='.{3,10}' tabindex='2' maxlength='10' value="<?php if(isset($_POST['CPassword'])){ echo $_POST['CPassword']; } ?>" placeholder="Repeat Your Password (max 10 char)" autocomplete='off' required />
                            <p>3 - 10 Characters | Letters or numbers only</p>
                        </div>
                    </li>
                        <li>
                            <div class='g-recaptcha' id='g-recaptcha' data-theme='dark'></div>
                        </li>
                   <br /> <li>
                        <p class='terms'>By clicking 'Play Now' I agree to the <a href='http://shaiyamasacre.xyz/tos.php' target='_blank'>Terms & Conditions</a> & <a href='http://shaiyamasacre.xyz/privacy.php' target='_blank'>Privacy Policy</a></p>
	<div class="btnWrap " id='Register'>
		<div class="btn">
			<div class="btnRight">
					<input type="submit" value='Play Now' name="Register" />
			</div>
		</div>
	</div>
                    </li>
                </ol>
            </form>
</div>
<!-- end register form -->
</body>
<script src='https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit' async defer></script>
    <script>
        var myCap, onloadCallback = function() {
            myCap = grecaptcha.render('g-recaptcha', {
                'sitekey': 'YOUR_RECAPTCHA_PUBLIC_KEY',
                'expired-callback': resetCap,
                'theme': 'dark'
            });
        };
        function resetCap(){
            grecaptcha.reset();
        }
    </script>
</html>
At the end of the file you have to replace YOUR_RECAPTCHA_PUBLIC_KEY with your real reCAPTCHA public key.
(The view, is a bit messy i know but didn't had time to make it a clean code and left my website div's in there).

Your file structure should be
-- Register
---- Inc
------ config.php
------ api.php
---- register.php

NOTE : this has included an email field in the database, you may remove it or create it according to your db structure. It does not include email verification process.

That's it,
Enjoy!
01/19/2016 23:37 st.jimmy998#2
Nice release treica :P
01/20/2016 07:41 SkuulCandy#3
Good ! :)
01/20/2016 12:02 Psycnosis#4
nice release, sorry to ask though, how secure is it from injections?
01/20/2016 16:36 treica#5
Quote:
Originally Posted by Psycnosis View Post
nice release, sorry to ask though, how secure is it from injections?
You can test the source code for vulnerabilities [Only registered and activated users can see links. Click Here To Register...].

Results for api.php
Code:
Line 23: PHP File Inclusion in 'file_get_contents' via '$captcha' (no risk)
Line 101: Cross-Site Scripting (XSS) in 'echo' via '$success' (no risk)
As long as the data is passed through a prepared statement is security risk free.

You could improve the connection settings by adding the setattribute and make sure your ini is set to UTF8 character set like so

Code:
<?
//	Connect to MSSQL
	$sqlUser  = 'YOUR_USER';
	$sqlPass  = 'YOUR_PASS';
        $IP = 'YOUR_IP';
	$database = 'PS_UserData';

	try {
		$conn  = new PDO("sqlsrv:Server=$IP;Database=$database", $sqlUser, $sqlPass);
                $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                ini_set('mssql.charset', 'UTF-8');
	}
	catch (PDOException $e){
    	die($e->getMessage());
	}
error_reporting(0);
?>
08/08/2018 06:35 DEEPDARKP#6
i get that script and i putted my recpatcha Key
and i change the Config file everything is right but when i press Play Now nothings work
can you help me please
10/04/2018 19:42 RapSandy#7
Download???
10/04/2018 20:01 {Skrillex}#8
Quote:
Originally Posted by RapSandy View Post
Download???
wanna kidding? This is a PHP Script. There is no download needed. Look at the source.
02/28/2019 02:16 jenny2011#9
why?
play now and

=== > prepare("SELECT Count(UserID) FROM dbo.Users_Master WHERE UserID = :Username"); $CheckUsername->bindParam(':Username', $user, PDO::PARAM_STR); $CheckUsername->execute(); $Number = $CheckUsername->fetchColumn(); //check the email if exists $CheckEmail = $conn->prepare("SELECT Count(Email) FROM dbo.Users_Master WHERE Email = :Email"); $CheckEmail->bindParam(':Email', $email, PDO::PARAM_STR); $CheckEmail->execute(); $mailCheck = $CheckEmail->fetchColumn(); //check the IP if exists if so, how many times? if there are 2 accounts we don't let to register another if($NumberIP[0] >= 1) should be edited to change $CheckIp = $conn->prepare("SELECT Count(UserUID) AS num_accs FROM Users_Master WHERE UserIp = :Ip"); $CheckIp->bindParam(':Ip', $ip, PDO::PARAM_STR); $CheckIp->execute(); $NumberIP = $CheckIp->fetch(PDO::FETCH_NUM); if($NumberIP[0] >= 4) { $e[] = "
You already have an account registered!
"; } // Validate data if($Number > 0) { $e[] = "
User name already exists, please choose a different user name.
"; } else if(empty($email)) { $e[] = "
Please provide an Email address
"; } else if($mailCheck > 0) { $e[] = "
This Email address already exists
"; } else if(empty($pw)) { $e[] = '
Please provide a password.
'; }else if(strlen($pw) < 3 || strlen($pw) > 16) { $e[] = '
Password must be between 3 and 16 characters in length.
'; }else if($pw != $rePw) { $e[] = '
Passwords do not match.
'; } else if(empty($user) || empty($pw) || empty($rePw)) { $e[] = "
Required fields cannot be empty!
"; } else if($response['success'] == false) { $e[] = "
Spam verification failed, please try again!
"; } else if(count($e) == 0) { $stmt = $conn->prepare("INSERT INTO Users_Master (UserID,Pw,JoinDate,Admin,AdminLevel,UseQueue,Stat us,Leave,LeaveDate,UserType,Point,EnPassword,UserI p,Email) VALUES (?,?,GETDATE(),0,0,0,0,0,GETDATE(),'N',0,'',?,?)") ; $params = array($user,$pw,$ip, $email); $stmt->execute($params); if($stmt == NULL) { $e[] = "
API Failed, please contact an administrator!
"; } else { $success = htmlentities("
Account {$user} successfully created!
"); } } // Determine which view to show. if($success === false){ require_once('../register.php'); }else{ $success = htmlentities("Account {$user} successfully created!"); echo "
".$success."
"; } } ?>



please help
02/28/2019 15:39 SnickQ#10
Short tag or <?php you need
08/28/2019 19:45 mikael0069#11
why do i always get this error ERROR for site owner: Invalid site key
08/30/2019 09:47 aipca#12
good job!