PHP / XMLHTTP Registration Check For Existing UN and Email

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

PHP / XMLHTTP Registration Check For Existing UN and Email

Post by Burrito »

I got sick of having to submit my forms when I am registering for a site only to find out that my username and/or email address is already in use so I got to thinking...would be nice to be able to check that stuff on the form page itself...I put together this simple registration page which checks the username and email (in realtime) to ensure it's not already taken prior to the form submission. Of course I still check on the server side (a double check :)).

lemme know what you think. BTW: I tried to run my checkIt() function using the onSubmit event and then return true or false instead of submitting the form from within my function, but couldn't get that to go. If you have better luck than I, please share.

see it working here

Code: Select all

 
<?php
$page = "register";
// include db connectivity schtuff...burrrito
require_once("../includes/dbInteract.php");
tt_db_connect();
// check if prelim is set (form check before submit)...burrito
if(isset($_POST['prelim'])){
    $un = TRUE;
    $em = TRUE;
    $msg = "";
    // check the username they're trying to use...burrito
    $getusername = mysql_query("select * from myTable where username = '" . mysql_escape_string($_POST['username']) . "'")
        or die(mysql_error());
    if($gtusername = mysql_fetch_assoc($getusername)){
        $un = FALSE;
    }
    // check the email they're trying to use...burrito
    $getemail = mysql_query("select * from myTable where email = '".mysql_escape_string($_POST['email'])."'")
        or die(mysql_error());
    if($gtemail = mysql_fetch_assoc($getemail)){
        $em = FALSE;
    }
    // check if either email or username failed, if so append to msg...burrito
    if(!$un || !$em){
        $unm = (!$un ? "That Username Is Already Taken, Please Enter A Different Username \n" : "");
        $emm = (!$em ? "That Email Address Is Already In Use On The System, Please Enter A Different Email Address" : "");
        $msg = $unm . $emm;
    }else{
        $msg = 1;
    }
    echo $msg;
    exit;
// prelim passed now check on server side for non-js users to ensure username and pass are unique...burrito
}else if(isset($_POST['username'])){
    $un = TRUE;
    $em = TRUE;
    $msg = 1;
    // check the username they're trying to use...burrito
    $getusername = mysql_query("select * from myTable where username = '".mysql_escape_string($_POST['username'])."'")
        or die(mysql_error());
    if($gtusername = mysql_fetch_assoc($getusername)){
        $un = FALSE;
    }
    // check the email they're trying to use...burrito
    $getemail = mysql_query("select * from myTable where email = '".mysql_escape_string($_POST['email'])."'")
        or die(mysql_error());
    if($gtemail = mysql_fetch_assoc($getemail)){
        $em = FALSE;
    }
    if(!$un || !$em){
        $unm = (!$un ? "That Username Is Already Taken, Please Enter A Different Username <br>" : "");
        $emm = (!$em ? "That Email Address Is Already In Use On The System, Please Enter A Different Email Address" : "");
        $msg = "<span style=\"color:#ff0000\">".$unm . $emm."</span>";
    }else{
        $msg = "Account Created Successfully";
        $hasbeen = 1;
    }
}
// stuff passed so insert new account to the database...burrito
if(isset($hasbeen)){
    mysql_query("insert into myTable
    (
    username,
    password,
    email
    )
    values
    (
    '".mysql_escape_string($_POST['username'])."',
    '".mysql_escape_string(md5($_POST['password']))."',
    '".mysql_escape_string($_POST['email'])."'
    )"
    )
        or die(mysql_error());
}
?>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 
<html>
<head>
    <title>Registration Sample</title>
<style>
td {
	font-family:tahoma; font-size:9.0pt;
}
th {
	font-family:tahoma; font-size:9.0pt;
}
body {
	background-color:#C9CBBD; margin:6px; font-family:tahoma; font-size:9.0pt; font-weight:bold;
}
.mainstuf {
	background-color:#ffffff;
}
input,textarea, select {
	color:#000000;
	font-size:9.0pt; font-family:tahoma, arial;
	border: 1px #3A3B29 solid;
	background-color:#CACAB5;
}
</style>
<script>
try{
    if (window.XMLHttpRequest){
        reqsend = new XMLHttpRequest();
    }else{
        reqsend = new ActiveXObject("Microsoft.XMLHTTP");
    }
}catch(e){
 
};
function checkIt(){
    var msg = "The Following Information Needs Attention \n";
    if(document.MyForm.username.value == "")
        msg += "You Must Enter A Username \n";
    if(document.MyForm.password.value == "")
        msg += "You Must Enter A Password \n";
    if(document.MyForm.password.value !== document.MyForm.password2.value)
        msg += "Passwords Do Not Match \n";
    if(document.MyForm.email.value == "")
        msg += "You Must Enter Your Email Address";
    if(msg.length > 55){
        alert(msg);
        return false;
    }
    try{
        reqsend.open("POST", "registration.php", true);
        var stuff = "prelim=1&username="+document.MyForm.username.value+"&email="+document.MyForm.email.value;
 
        reqsend.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        reqsend.setRequestHeader("Content-Length",stuff.length);
        reqsend.send(stuff);
        
        reqsend.onreadystatechange = function(){
            if (reqsend.readyState == 4 && reqsend.status == 200) {
                if(reqsend.responseText == 1){
                    document.MyForm.submit();
                }else{
                    alert(reqsend.responseText);                
                    return false;
                }
 
            }
        };
    }catch(e){
        document.MyForm.submit();
    }
}
 
</script>
</head>
 
<body>
            <form name="MyForm" action="registration.php" method="post">
            <table width="500" align="center" class="maint" cellspacing="0">
            <?if(isset($msg)){?>
            <tr>
            <td align="center"><?=$msg;?></td>
            </tr>
            <?}
            if(!isset($hasbeen)){?>
            <tr>
            <th colspan="2">Register For Our Website</th>
            </tr>
            <tr>
            <td>Enter a username:</td><td align="right"><input type="text" name="username"></td>
            </tr>
            <tr>
            <td>Enter a password:</td><td align="right"><input type="password" name="password"></td>
            </tr>
            <tr>
            <td>Confirm password:</td><td align="right"><input type="password" name="password2"></td>
            </tr>
            <tr>
            <td>Enter your email address:</td><td align="right"><input type="text" name="email" size="35"></td>
            </tr>
            <tr>
            <td colspan="2" align="center"><input type="button" value="Register" onClick="checkIt()"></td>
            </tr>
            <?} // end if for hasbeen is set...burrito ?>
            </table>
            </form>
        
</body>
</html>

 
see it working here

enjoy,

Burr

another BTW: I don't actually insert a row on the sample, so if you try it and then try it again with the same username, it'll allow it again...only "bob smith" and "bob@bob.com" will die.
Last edited by Weirdan on Sat Aug 28, 2010 12:23 pm, edited 1 time in total.
Reason: fixed multiple html encoding issues
method_man
Forum Contributor
Posts: 257
Joined: Sat Mar 19, 2005 1:38 am

nice

Post by method_man »

nice :D

matt
The Monkey
Forum Contributor
Posts: 168
Joined: Tue Mar 09, 2004 9:05 am
Location: Arkansas, USA

Post by The Monkey »

Hey Burrito, this is really sweet. As much as I dislike the concept of javascript itself, in practice it can be impressively useful.

I'm going to use your concept on a somewhat small project here in a few days, and if I have more luck with the onsubmit handler, I'll be sure to let you know. Thanks a bunch for the idea and example script, it is coming in very useful. :)

- Monkey
User avatar
protokol
Forum Contributor
Posts: 353
Joined: Fri Jun 21, 2002 7:00 pm
Location: Cleveland, OH
Contact:

Post by protokol »

We use the XML HTTP Request in Javascript in a few different intranet applications at work. We've found that it's extremely useful for dynamically filling dropdown boxes based on a selected dropdown, etc. Also, for things like looking up order numbers or customer numbers, it's fantastic. Page loads are reduced and user-experience is enhanced. I definitely recommend learning it because it's really cool technology.
MichaelR
Forum Contributor
Posts: 148
Joined: Sat Jan 03, 2009 3:27 pm

Re: PHP / XMLHTTP Registration Check For Existing UN and Email

Post by MichaelR »

Could this be edited by a moderator so that it shows as code instead of as text? And to fix the "&quote" problem.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: PHP / XMLHTTP Registration Check For Existing UN and Email

Post by pickle »

Tags have been updated, but the escaped html characters will take longer than I care to give it.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
MichaelR
Forum Contributor
Posts: 148
Joined: Sat Jan 03, 2009 3:27 pm

Re: PHP / XMLHTTP Registration Check For Existing UN and Email

Post by MichaelR »

With the html characters fixed:

Code: Select all

<?
 
$page = "register";
// include db connectivity schtuff...burrrito
require_once("../includes/dbInteract.php");
tt_db_connect();
// check if prelim is set (form check before submit)...burrito
if(isset($_POST['prelim'])){
    $un = TRUE;
    $em = TRUE;
    $msg = "";
    // check the username they're trying to use...burrito
    $getusername = mysql_query("select * from myTable where username = '".mysql_escape_string($_POST['username'])."'")
        or die(mysql_error());
    if($gtusername = mysql_fetch_assoc($getusername)){
        $un = FALSE;
    }
    // check the email they're trying to use...burrito
    $getemail = mysql_query("select * from myTable where email = '".mysql_escape_string($_POST['email'])."'")
        or die(mysql_error());
    if($gtemail = mysql_fetch_assoc($getemail)){
        $em = FALSE;
    }
    // check if either email or username failed, if so append to msg...burrito
    if(!$un || !$em){
        $unm = (!$un ? "That Username Is Already Taken, Please Enter A Different Username \n" : "");
        $emm = (!$em ? "That Email Address Is Already In Use On The System, Please Enter A Different Email Address" : "");
        $msg = $unm . $emm;
    }else{
        $msg = 1;
    }
    echo $msg;
    exit;
// prelim passed now check on server side for non-js users to ensure username and pass are unique...burrito
}else if(isset($_POST['username'])){
    $un = TRUE;
    $em = TRUE;
    $msg = 1;
    // check the username they're trying to use...burrito
    $getusername = mysql_query("select * from myTable where username = '".mysql_escape_string($_POST['username'])."'")
        or die(mysql_error());
    if($gtusername = mysql_fetch_assoc($getusername)){
        $un = FALSE;
    }
    // check the email they're trying to use...burrito
    $getemail = mysql_query("select * from myTable where email = '".mysql_escape_string($_POST['email'])."'")
        or die(mysql_error());
    if($gtemail = mysql_fetch_assoc($getemail)){
        $em = FALSE;
    }
    if(!$un || !$em){
        $unm = (!$un ? "That Username Is Already Taken, Please Enter A Different Username <br>" : "");
        $emm = (!$em ? "That Email Address Is Already In Use On The System, Please Enter A Different Email Address" : "");
        $msg = "<span style=\"color:#ff0000\">".$unm . $emm."</span>";
    }else{
        $msg = "Account Created Successfully";
        $hasbeen = 1;
    }
}
// stuff passed so insert new account to the database...burrito
if(isset($hasbeen)){
    mysql_query("insert into myTable
    (
    username,
    password,
    email
    )
    values
    (
    '".mysql_escape_string($_POST['username'])."',
    '".mysql_escape_string(md5($_POST['password']))."',
    '".mysql_escape_string($_POST['email'])."'
    )"
    )
        or die(mysql_error());
}
?>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 
<html>
<head>
    <title>Registration Sample</title>
<style>
td
{
font-family:tahoma; font-size:9.0pt;
}
th
{
font-family:tahoma; font-size:9.0pt;
}
body
{
background-color:#C9CBBD; margin:6px; font-family:tahoma; font-size:9.0pt; font-weight:bold;
}
.mainstuf
{
background-color:#ffffff;
}
input,textarea, select
{
color:#000000;
font-size:9.0pt; font-family:tahoma, arial;
border: 1px #3A3B29 solid;
background-color:#CACAB5;
}
</style>
<script>
try{
    if (window.XMLHttpRequest){
        reqsend = new XMLHttpRequest();
    }else{
        reqsend = new ActiveXObject("Microsoft.XMLHTTP");
    }
}catch(e){
 
};
function checkIt(){
    var msg = "The Following Information Needs Attention \n";
    if(document.MyForm.username.value == "")
        msg += "You Must Enter A Username \n";
    if(document.MyForm.password.value == "")
        msg += "You Must Enter A Password \n";
    if(document.MyForm.password.value !== document.MyForm.password2.value)
        msg += "Passwords Do Not Match \n";
    if(document.MyForm.email.value == "")
        msg += "You Must Enter Your Email Address";
    if(msg.length > 55){
        alert(msg);
        return false;
    }
    try{
        reqsend.open("POST", "registration.php", true);
        var stuff = "prelim=1&amp;username="+document.MyForm.username.value+"&amp;email="+document.MyForm.email.value;
 
        reqsend.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        reqsend.setRequestHeader("Content-Length",stuff.length);
        reqsend.send(stuff);
       
        reqsend.onreadystatechange = function(){
            if (reqsend.readyState == 4 &amp;&amp; reqsend.status == 200) {
                if(reqsend.responseText == 1){
                    document.MyForm.submit();
                }else{
                    alert(reqsend.responseText);               
                    return false;
                }
 
            }
        };
    }catch(e){
        document.MyForm.submit();
    }
}
 
</script>
</head>
 
<body>
            <form name="MyForm" action="registration.php" method="post">
            <table width="500" align="center" class="maint" cellspacing="0">
            <?if(isset($msg)){?>
            <tr>
            <td align="center"><?=$msg;?></td>
            </tr>
            <?}
            if(!isset($hasbeen)){?>
            <tr>
            <th colspan="2">Register For Our Website</th>
            </tr>
            <tr>
            <td>Enter a username:</td><td align="right"><input type="text" name="username"></td>
            </tr>
            <tr>
            <td>Enter a password:</td><td align="right"><input type="password" name="password"></td>
            </tr>
            <tr>
            <td>Confirm password:</td><td align="right"><input type="password" name="password2"></td>
            </tr>
            <tr>
            <td>Enter your email address:</td><td align="right"><input type="text" name="email" size="35"></td>
            </tr>
            <tr>
            <td colspan="2" align="center"><input type="button" value="Register" onClick="checkIt()"></td>
            </tr>
            <?} // end if for hasbeen is set...burrito ?>
            </table>
            </form>
       
</body>
</html>
Post Reply