Registration PHP Code for Multiple PSB Hosts with Captcha
Registering for a PSB account using a captcha is only logical—you don't want those infernal spambots registering for a PSB! For info on the registration script on this page, check out our Registration PHP Code for Multiple PSB Hosts page. The only code discussed on this page is the captcha code. This page's script is basically our PSB registration script for multiple PSB hosts PLUS the needed captcha script to keep away spambots. The captcha code is in red, to make it easy to understand the way a captcha influences a PHP page of code.
If the person registering gets the captcha right, the PHP flag $cap is set to 1. Otherwise it's set to zero when the registrating person fails to solve the captcha.
Almost right off the bat we check to see if this page has POSTed the value of the $cap flag back to itself. If not, we skip the table creation aspect of the registration script and, after the JavaScript functions have been declared, head for the captcha script. Note that in the registration script, once an administrator is registered, the $cap flag is set back to 0 so the captcha will show up again and the registration form will NOT show up. Perhaps a person wants to register for more than one PSB group. Note the third curly bracket is red after the registration script. It represents the far end of the if($cap == 1){ clause. Also check out the form at the end. In order to keep the current status of the $cap flag intact, we stick a hidden field into the form that sends a "1" value for the field whose name is "cap" so it will be POSTed back to the front of the script after the submission reloads the page, and this reminds the page that the captcha was solved, which allows the actual MySQL table creations to actualize at the beginning of the script. Similarly, we used hidden fields to send the current value of "cap" to the script in the captcha's form.
So wrong captcha solutions, like form submissions, cause page reloads. This makes sense when you look at the captcha code which includes an HTML form submission. Note that the captcha code starts by letting the PSB aspirant into the captcha if he has not solved it yet (or if he has solved it and completed registering so he's eligible for more registration action). Also note that the HTML form is split with PHP captcha code in between. Isn't it cool how all these languages can climb into the same sandbox and play nice together? Actually, it's not that simple—we tried dozens of mixed-language codes together that did NOT play nice and caused either syntax errors or total disaster. We can't say if we would have seen what was annoying the language smorgasbord better if we'd have had more PHP experience, or if it's a really complex code and anyone would have had to try lots of combos to get it to work. But who cares? Phenomenal persistance is the most critical characteristic of programmers. Like they say: success is 10% inspiration and 90% perspiration.
So the captcha form tag has an id named "oo" (named for our exclamation when we figured out that the CSS property visibility was key to having the captcha go away when the data input form was active). Notice how this property is set to "hidden" once the captcha is solved. Nowhere on the page does it get reset to "visible," but it need not do so because the data form will get submitted after the captcha solution, which reloads the page and when the captcha appears again it's because visibility is the default state of objects and the page has not yet set the CSS property visibility to "hidden."
The captcha sign-up process is painless enough—and free. You get some codes, examples, and a library to use (recaptchalib.php) to help you protect your pages with captchas. You get a public key and a private key; both are strings of random-looking characters, which are definitely NOT the "yourcaptchaaccountspublickey" and "yourcaptchaaccntsprivatekey" you see below. This seemed to be a more sensible replacement for these codes than "aseeminglyrandomstringofcharactersohmygodwhataretheydoing?". Anyway, in their example, they had an 'if/else" conditional wherein if your solution was good, you inserted a simple few lines of code to send an email or grab a couple of inputs via a form, but if your solution sucked, you got a nasty letter, the cops were called on you, and your pet dog died. JUST KIDDING! Failure gave you a polite "incorrect solution—please try again" message. This was all well and good if you had a simple mail-to script or a couple of input boxes, but we had lots of HTML and JavaScript and PHP scripts that needed to be utilized during registration, and this did not work by following their example, so we had to punt. The first step was to set a flag reflecting the result rather than trying to insert a language smorgasbord in the middle of their codes. This way we could run various codes or display various forms according to our captcha success. Note that we even had to have 2 versions of the second half of their captcha form's HTML code, depending on their success. The registration form being shown onscreen depended on the $cap flag being set to 1, for instance.
<?
include_once"configure.php";
$sql = "CREATE TABLE IF NOT EXISTS members (
id int(11) NOT NULL auto_increment,
username varchar(255) NOT NULL,
admin_password varchar(255) NOT NULL,
users_password varchar(255) NOT NULL,
email varchar(255) NOT NULL,
ip varchar(255) NOT NULL,
date varchar(255) NOT NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM AUTO_INCREMENT=1";
// Execute query
mysql_query($sql);
$cap=$_POST['cap'];
if($cap == 1){
if(isset($_POST['register'])){
$username = $_POST['username'];
$password = $_POST['admin_password'];
$upassword = $_POST['users_password'];
$email = $_POST['email'];
$memip = $_SERVER['REMOTE_ADDR'];
$date = date("d-m-Y");
$checkformembers = mysql_query("SELECT * FROM members WHERE username = '$username'");
if(mysql_num_rows($checkformembers) != 0){echo '<script language="javascript">alert("Username already in use. Please try again.")</script>;';
}else{
$num=$_POST['num'];
$a=$username."_psb";
$sql = "CREATE TABLE $a
(
N int(2) NOT NULL AUTO_INCREMENT,
Firstname varchar(12) NOT NULL,
ID int(2) NOT NULL,
Status char(2) NOT NULL,
Comment varchar(55) NOT NULL,
PRIMARY KEY(N)
)";
// Execute query
mysql_query($sql);
$myArray=array();$myArray1=array();
for($i=0;$i<$num;$i++){
array_push ($myArray, $_POST['people'][$i]);
}
$myArray1=array_keys(array_flip($myArray));//array_unique has BUG!
$c=count($myArray1);
if($num>$c){echo '<script language="javascript">alert("One or more duplicate names were deleted.");</script>';}
for($i=0;$i<$c;$i++){
$b=$myArray1[$i];
$j= $i + 1;
mysql_query("INSERT INTO $a (N, Firstname, ID, Status, Comment)
VALUES('','$b','$j','99','')");
}
$a=$username."_meaning";
$sql = "CREATE TABLE $a
(
sorter int(3) NOT NULL,
meaning varchar(57) NOT NULL,
PRIMARY KEY(sorter)
)";
// Execute query
mysql_query($sql);
mysql_query("INSERT INTO $a (sorter, meaning)
VALUES ('1','Alone (do not disturb)'),('2','Alone thinking'),('3','Alone with someone'),('4','Alone creating'),('5','Alone sleeping'),('6','Alone studying'),('7','Alone exercising'),('8','Alone feelings (sad or lonely or depressed)'),('9','Alone feelings (anxious or confused or fearful or upset)'),('10','Alone feelings (need help)'),('11','Want nurturing'),('12','Will nurture'),('13','Could nurture'),('14','I am a scheduled caregiver'),('15','Sick - need care'),('16','Sick - have care'),('17','Want stories'),('18','Will read stories'),('19','Want massage'),('20','I am being nurtured'),('21','Want P.E.T. training'),('22','Will train re: P.E.T.'),('23','Need to do problem solving'),('24','Will help problem-solve'),('25','Need active listening'),('26','Will active listen'),('27','Doing authoritative parenting activity - not P.E.T.'),('28','Want help with discipline'),('29','Will give help with discipline'),('30','Doing P.E.T. activity'),('31','Want advice'),('32','Will advise'),('33','Want group discussion'),('34','Want to talk with female'),('35','Want to talk with male'),('36','Want adult company'),('37','Want child company'),('38','Want to play'),('39','Want to play game(s)'),('40','I am in meeting'),('41','Let Us Coordinate MC party'),('42','Let Us Coordinate MC big dinner'),('43','Let Us Coordinate MC all-MC meeting'),('44','Let Us Coordinate MC MC projects'),('45','Let Us Coordinate MC music'),('46','Let Us Coordinate MC creative projects'),('47','Let Us Coordinate MC activity - open to possibilities'),('48','Let Us Coordinate MC movie in theater'),('49','Let Us Coordinate MC DVD movie on TV'),('50','I am in MC coordinating meeting'),('51','Let Us Coordinate shopping - food'),('52','Let Us Coordinate shopping - clothes'),('53','Let Us Coordinate shopping - other'),('54','Let Us Coordinate going to library'),('55','Let Us Coordinate going to concert'),('56','Let Us Coordinate going to movie'),('57','Let Us Coordinate playing sports'),('58','Let Us Coordinate seeing sporting event'),('59','Let Us Coordinate exercise'),('60','Let Us Coordinate other'),('61','I am Out at school or daycare'),('62','I am Out at work'),('63','I am Out at shopping'),('64','I am Out at library'),('65','I am Out at entertainment'),('66','I am Out with friends or date'),('67','I am Out at hospital'),('68','I am Out at vacation - out of town'),('69','I am Out at doctor'),('70','I am Out at other'),('71','Want Ride north - A.M.'),('72','Want Ride north - P.M.'),('73','Want Ride south - A.M.'),('74','Want Ride south - P.M.'),('75','Want Ride east - A.M.'),('76','Want Ride east - P.M.'),('77','Want Ride west - A.M.'),('78','Want Ride west - P.M.'),('79','Want Ride motorcycle OK'),('80','Want Passenger(s) - I will drive'),('81','Want help with project'),('82','Will help with project'),('83','Want tutor in music'),('84','Want tutor in math'),('85','Want tutor in science'),('86','Want tutor in languages'),('87','Want tutor in English or literature'),('88','Want tutor in history'),('89','Want tutor in taxes'),('90','Will tutor'),('91','Need pet caretaker'),('92','Am texting'),('93','Text me'),('94','Am emailing'),('95','Email me'),('96','Am IMing'),('97','IM me'),('98','Surfing the Net'),('99','Writing a letter'),('100','All is well')
");
$create_member = mysql_query("INSERT INTO members (id, username, admin_password, users_password, email, ip, date)
VALUES('','$username','$password','$upassword','$email','$memip','$date')");
echo '<script language="javascript">alert("Thank you for registering. Please login.");</script>';
$cap=0;
$to = $email;
$subject = "Welcome, new PSB administrator!";
$message = "You've successfully registered as administrator of a PSB group.\n\nYour user name is ".$username.".\n\nYou may use your admin password to edit your account settings, add people to your PSB, edit status code meanings, change your email, or even delete your whole account.\n\nDon't give your admin password to anyone in your group, but do save it somewhere safe.\n\nGive your group members the users password ONLY.\n\nYou and your group may use this users password to log in to your PSB and change your status and comments.\n\nEnjoy your PSB.\n\nRegards,\n\nthe management";
$headers = "From: ".$psbhostemailaddress."\r\nReply-To: ".$email;
$mail_sent = mail($to, $subject, $message, $headers);
}}}
mysql_close();
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>PSB Signup Script</title>
<script language="javascript">
document.onkeydown = function(e){
e = e? e : window.event;
var k = e.keyCode? e.keyCode : e.which? e.which : null;
if (k == 13){
if (e.preventDefault) e.preventDefault();
return false;}
return true;}
var flag=0;var clik=0;
function validate(field){
var ck_userfirstname = /^[A-Za-z0-9_]{1,12}$/;
if (field.value.search(ck_userfirstname)==-1)
{field.value='';alert("Please only enter letters, numbers and underline for user first names, and enter 1 to 12 characters.");};flag=flag+1;}
function validatepassword(){
if(clik==0||clik<num_people){alert("Please enter number of people to add.");return false}
if(flag==0){alert("Please only enter letters, numbers and underline for user first names, and enter 1 to 12 characters.");return false}
var ck_username = /^[A-Za-z0-9_]{4,30}$/;
if (document.peopleForm.username.value.search(ck_username)==-1)
{alert("Please only enter letters, numbers and underline for user names, and enter 4 to 30 characters.");return false}
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,12}$/;
if (document.peopleForm.users_password.value.search(ck_password)==-1)
{alert("Please only enter 6 to 12 letters, numbers and these for user password: !@#$%^&*()_");return false}
var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,12}$/;
if (document.peopleForm.admin_password.value.search(ck_password)==-1)
{alert("Please only enter 6 to 12 letters, numbers and these for administrator password: !@#$%^&*()_");return false}
var ck_email = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
if (document.peopleForm.email.value.search(ck_email)==-1)
{alert("That email address is not valid.");return false}
return true}
var num_people=0;
function CreateFormTextInput (its_name,t) {
var formField = document.createElement ("input");
formField.setAttribute ('type', 'text');
formField.setAttribute ('value', "");
formField.setAttribute ('name', its_name);
formField.setAttribute ('size', '12');
formField.style.cssText = 'position:absolute;left:322px;top:'+t+'px;';
formField.onblur=function(){validate(this);};
e = document.getElementById("form");
z=t+26;
e.style.height=z+"px";
return formField;
}
function AddFormFields (num_people){
for(i=0;i<num_people;i++){
var d= 280+(i*22);
var a = 'people[]'; a = a.toString();
var textBox = CreateFormTextInput(a,d);
var br = document.createElement("br");
document.peopleForm.appendChild(br);
document.peopleForm.appendChild(textBox);}}
Netscape=(navigator.appName.indexOf("Netscape") != -1)
function fix(){if(Netscape){e=document.getElementById('side');e.style.width='122px';}}
</script>
</head>
<body onload='fix()'>
<?php
if($cap!=1){
?>
<form id="oo" name="cform" style='position:absolute;left:400px;top:400px' action="" method="post">
<?php
$cap=0;
require_once('recaptchalib.php'); // supplied when you register
// with http://recaptcha.net/
$publickey = "yourcaptchaaccountspublickey";// supplied when you register
$privatekey = "yourcaptchaaccntsprivatekey";//supplied when you register
# the response from reCAPTCHA
$resp = null;
# the error code from reCAPTCHA, if any
$error = null;
# are we submitting the page?
if ($_POST["submit"]) {
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {$cap=0;$error = $resp->error;}
else {$cap=1;}
}
echo recaptcha_get_html($publickey, $error);
if($cap==1){
?>
<br>
<input type="hidden" name="cap" value="1">
<input type="submit" name="submit" value="submit">
</form>
<script language="javascript">
e=document.getElementById('oo');e.style.visibility='hidden';
</script>
<?php
}
if($cap==0){
?>
<br>
<input type="hidden" name="cap" value="0">
<input type="submit" name="submit" value="submit">
</form>
<?php
}}
if($cap==1){
?>
<div style='position:absolute;left:150px;top:15px;'>
<form name="peopleForm" id='form' method="post" onsubmit="return validatepassword()" action="register-with-captcha.php" style='background-color:#ccc;border:4px solid blue;width:700px;'>
<table width="600" border="1" align="center">
<tr>
<td width="50%">Username:</td>
<td width="50%"><label>
<input name="username" type="text" id="username" size="30">
</label></td>
</tr>
<tr>
<td>Administrator's Password:</td>
<td><input name="admin_password" type="password" id="password" value="" size="30"></td>
</tr>
<tr>
<td>User's Password:</td>
<td><input name="users_password" type="password" id="u_password" value="" size="30"></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="email" type="text" id="email" size="30"><input name="cap" type="hidden" value="1"></td>
</tr>
<tr>
<tr>
<td>Number of people to add:</td>
<td><input name="num" type="text" id="num" size="30" value=''><input type="button" value="Add people before Registering" onclick="clik=1;AddFormFields(document.peopleForm.num.value)"></td>
</tr>
<tr>
<td> </td>
<td><label>
<input name="register" type="submit" id="register" value="Register">
</label> as Administrator of a PSB group.</td>
</tr>
</table>
</form>
</div>
<div id='side' style='position:absolute;left:0px;top:15px;padding:12px;background-color:#eee;border:1px solid black;width:140px;'>Administrator: If you want your status to be part of your PSB, include your first name with the others in "Add people before Registering". Use the User's Password to login.</div>
<?php
}
?>
</body>
</html>