Making a PHP/MySQL/JQuery Form Require _ In The Middle of Username

Hello, I have a MySQL/PHP/JQuery form which enters the registration information into my database table. I was wondering if it is possible to make it so the “Username” field requires the special character _ in the middle of the name, example: John_Jones, and the first and second characters of the name (before and after _) needs to be 4 or more characters long.
Here is what I have at the moment:

[code]else if($_POST[‘submit’]==‘Register’)
{
// If the Register form has been submitted

$err = array();

if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32)
{
	$err[]='Your username must be between 43 and 32 characters!';
}

if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
	$err[]='Your username contains invalid characters!';
}

if(!checkEmail($_POST['email']))
{
	$err[]='Your email is not valid!';
}

if(!count($err))
{
	// If there are no errors
	
	$pass = substr(sha1($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
	// Generate a random password
	
	$_POST['email'] = mysql_real_escape_string($_POST['email']);
	$_POST['username'] = mysql_real_escape_string($_POST['username']);
	// Escape the input data
	
	
	mysql_query("	INSERT INTO playerdata(user,password,email, ip)
					VALUES(
					
						'".$_POST['username']."',
						'".sha1($pass)."',
						'".$_POST['email']."',
						'".$_SERVER['REMOTE_ADDR']."'
						
					)");
	
	if(mysql_affected_rows($link)==1)
	{
		send_mail(	'[email protected]',
					$_POST['email'],
					'Registration System Demo - Your New Password',
					'Your password is: '.$pass);

		$_SESSION['msg']['reg-success']='Email sent with pass. '.$pass;
	}
	else $err[]='This username is already taken!';
}

if(count($err))
{
	$_SESSION['msg']['reg-err'] = implode('<br />',$err);
}	

header("Location: demo.php");
exit;

}[/code]

Any help would be greatly appreciated, I am a very fast learner.

Ahpex,

It is not entirely clear what you’re trying to achieve.

You want users to have a username of the following structure: user_name … why?

For this simple case this can easily be checked using the strpos and strlen functions.

But you are not very clear on what you do with special cases: user_for_life, is that a valid username? Or can a username only have 1 underscore?

And what about the following username: user_for_all, this has more than 4 characters after the first underscore, but less than 4 after the last underscore.

And if you only want to look at the first underscore, would the following username be valid: user_jon_, 4 characters after the first underscore, but ended with an underscore.

It would be fairly easy to validate the structure of the username in a separate check, but it has to be based on what you want to achieve precisely. And this will require some custom coding. So in short: is this a restriction you really want to have? And if so, what is precisely the rule that you want to enforce?

Sorry, a little more of an explanation here.

I want it so the username contains only one underscore in the middle of the name with 4 characters or more on both sides of the underscore like John_Adam, so that John_Adam_ or John_Test_Adam is incorrect.

JohnAdam < need an underscore inbetween each 4 characters
John_Ada < not enough characters
John_Adam_ < too many underscores
John_Adam < correct.

I hope this isn’t too complicating to add but I’m more of a html web designer and just downloaded this register/login panel and edited the MySQL and text side of it, no idea about checking for the username syntax involving underscores and character lengths before and after the underscore.
Thanks.

This is not peoples real names, it’s for a GTA San Andreas Multiplayer roleplaying game server I have set up with my register/login script (UCP) via MySQL.

Does the underscore have to be in the center or just a minimum of 4 characters on either side?

[php]
$usernames = array(
‘JohnAdam’,
‘John_Ada’,
‘Jon_Ada’,
‘Jon_Adam’,
‘John_Adam_’,
‘John_Adam’,
‘John__Adam’,
‘John_Test_Adam’
);

foreach($usernames as $username) {
echo $username . ": " . (preg_match(’/^[A-Za-z0-9]{4,}_{1}[A-Za-z0-9]{4,}$/’, $username) ? “Valid” : “Invalid”) . “\n”;
}
[/php]

JohnAdam: Invalid
John_Ada: Invalid
Jon_Ada: Invalid
Jon_Adam: Invalid
John_Adam_: Invalid
John_Adam: Valid
John__Adam: Invalid
John_Test_Adam: Invalid

Matt, wouldn’t that make it so the only valid useable name is “John_Adam”?

On this roleplaying server I have scripted I need people to use any real life name (using an underscore instead of a space), so the only username syntax that would be available is like Carl_Smith, sorry I mean the minimum character requirement is no less than 4 characters and no more than 9 for the first name and no less than 4 and no more than 9 for the second. Is this possible in PHP?

Like:

Car_Smith < first name less than 4 characters, invalid.
Carl_Smi < second name less than 4 characters, invalid.
Carl_Smith (or Carl_Smith, or Carl_Smith) < too many underscores, invalid.
CarlSmith_ (or _CarlSmith, or CarlSmith) < underscore not in middle of the name, invalid.
Carl_Smith < underscore in middle of the name and both names over 4 characters and under 9, valid.

If you break down the regular expression you can see it does everything you are asking.

^ beginning of string
[A-Za-z0-9]{4,} must be alphanumeric and a length of 4 or more
_{1} must be 1 underscore
[A-Za-z0-9]{4,} same as first
$ end of string

You should remove 0-9 if you do not want to allow numbers. You can limit between 4 and 9 sure. Instead of {4,} it would be {4,9}

[php]
$usernames = array(
‘___________’,
‘a_b’,
‘aa_bb’,
‘aaaa_b’,
‘aaaa_bbb’,
‘aaaa_bbbb’,
‘aaaaaaaaa_bbbbbbbbb’,
‘aaaaaaaaaa_bbbb’
);

foreach($usernames as $username) {
echo $username . ": " . (preg_match(’/^[A-Za-z0-9]{4,9}_{1}[A-Za-z0-9]{4,9}$/’, $username) ? “Valid” : “Invalid”) . “\n”;
}
[/php]

___________: Invalid
a_b: Invalid
aa_bb: Invalid
aaaa_b: Invalid
aaaa_bbb: Invalid
aaaa_bbbb: Valid
aaaaaaaaa_bbbbbbbbb: Valid
aaaaaaaaaa_bbbb: Invalid

Thanks man, which part of the code do I replace it with? I’ve been reading through my script for like 8 hours non stop, this is how I learn, just need a bit of a boost for more of an understanding. Also, why does this return ‘0’ when I edit my users “money” row to “200” via phpmyadmin?:

[php]$result = mysql_query(“SELECT * FROM playerdata”);
$row = mysql_fetch_array($result);
echo “

” . $row[‘money’] . “

”;[/php]

I am assuming it’s because I haven’t defined the username in the query, but if the variable is $_SESSION[‘user’] to determine who is who, what would be the correct syntax (or even the correct code) for returning the amount of money stored in the database table “playerdata”? Cheers!

With these two issues solved I will have much more of an understanding on the correct syntax’s and how MySQL actually works, just a little complicating on some parts at the moment.

You want to replace your current username validation code:

[php]
if(strlen($_POST[‘username’])<4 || strlen($_POST[‘username’])>32)
{
$err[]=‘Your username must be between 43 and 32 characters!’;
}

if(preg_match(’/[^a-z0-9-_.]+/i’,$_POST[‘username’]))
{
$err[]=‘Your username contains invalid characters!’;
}
[/php]

The new regex will replace both of these. For example:

[php]
if (!preg_match(’/^[A-Za-z]{4,9}_{1}[A-Za-z]{4,9}$/’, $_POST[‘username’])) {
$err[] = ‘Your username is invalid.’;
}
[/php]

For your other problem, I assume you want something like this…

[php]
$query = sprintf(“SELECT * FROM playerdata WHERE userField = ‘%s’”, $_SESSION[‘user’]);
$result = mysql_query($query)or die(mysql_error());
[/php]

Hmm that username script you gave allows me to create any username and I need a script to echo how much money is stored in the database when logging in (I know where to place the code just can’t get the money amount to show in the table).

I have all the necessary .js and .css files, but here is the register/login script itself:

[php]<?php

error_reporting(E_ALL ^ E_NOTICE);
define(‘INCLUDE_CHECK’,true);

require ‘connect.php’;
require ‘functions.php’;
// Those two files can be included only if INCLUDE_CHECK is defined

session_name(‘tzLogin’);
// Starting the session

session_set_cookie_params(27246060);
// Making the cookie live for 2 weeks

session_start();

if($_SESSION[‘id’] && !isset($_COOKIE[‘tzRemember’]) && !$_SESSION[‘rememberMe’])
{
// If you are logged in, but you don’t have the tzRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:

$_SESSION = array();
session_destroy();

// Destroy the session

}

if(isset($_GET[‘logoff’]))
{
$_SESSION = array();
session_destroy();

header("Location: http://127.0.0.1/");
exit;

}

if($_POST[‘submit’]==‘Login’)
{
// Checking whether the Login form has been submitted

$err = array();
// Will hold our errors


if(!$_POST['username'] || !$_POST['password'])
	$err[] = 'All fields are required.';

if(!count($err))
{
	$_POST['username'] = mysql_real_escape_string($_POST['username']);
	$_POST['password'] = mysql_real_escape_string($_POST['password']);
	$_POST['rememberMe'] = (int)$_POST['rememberMe'];
	
	// Escaping all input data

	$row = mysql_fetch_assoc(mysql_query("SELECT * FROM playerdata WHERE user='{$_POST['username']}' AND password='".sha1($_POST['password'])."'"));

	if($row['user'])
	{
		// If everything is OK login
		
		$_SESSION['user'] = $row['user'];
		$_SESSION['money'] = $row['money'];
		$_SESSION['id'] = $row['id'];
		$_SESSION['score'] = $row['score'];
		$_SESSION['rememberMe'] = $_POST['rememberMe'];
		
		// Store some data in the session
		
		setcookie('tzRemember',$_POST['rememberMe']);
	}
	else $err[]='You have entered an invalid username or password.';
}

if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session

header("Location: http://127.0.0.1/");
exit;

}
else if($_POST[‘submit’]==‘Register’)
{
// If the Register form has been submitted
$err = array();

if(strlen($_POST['username'])< 9 || strlen($_POST['username'])> 18)
{
	$err[]='Your username must be between 9 and 18 characters.';
}

if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
	$err[]='Your username contains invalid characters.';
}

if(!checkEmail($_POST['email']))
{
	$err[]='Your email address is not valid.';
}

if(!count($err))
{
	// If there are no errors
	
	$pass = substr(sha1($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
	// Generate a random password
	
	$_POST['email'] = mysql_real_escape_string($_POST['email']);
	$_POST['username'] = mysql_real_escape_string($_POST['username']);
	// Escape the input data
	
	
	mysql_query("	INSERT INTO playerdata(user,password,level,money,email,ip,datetime)
					VALUES(
					
						'".$_POST['username']."',
						'".sha1($pass)."',
						'0',
						'20',
						'".$_POST['email']."',
						'".$_SERVER['REMOTE_ADDR']."',
						NOW()
						
					)");
	
	if(mysql_affected_rows($link)== 1)
	{
		send_mail(	'[email protected]',
					$_POST['email'],
					'Welcome to Domination Roleplay.',
					'Your password is: '.$pass);

		$_SESSION['msg']['reg-success']='An email has been sent containing your password. '.$pass;
	}
	else $err[]='That username has already been taken.';
}

if(count($err))
{
	$_SESSION['msg']['reg-err'] = implode('<br />',$err);
}	

header("Location: http://127.0.0.1/");
exit;

}

$script = ‘’;

if($_SESSION[‘msg’])
{
// The script below shows the sliding panel on page load

$script = '
<script type="text/javascript">

	$(function(){
	
		$("div#panel").show();
		$("#toggle a").toggle();
	});

</script>';

}
?>

The Sliding jQuery Panel

A register/login solution

You are free to use this login and registration system in you sites!

A Big Thanks

This tutorial was built on top of Web-Kreation's amazing sliding panel.

        <?php
		
		if(!$_SESSION['id']):
		
		?>
        
		<div class="left">
			<!-- Login Form -->
			<form class="clearfix" action="" method="post">
				<h1>Member Login</h1>
                
                <?php
					
					if($_SESSION['msg']['login-err'])
					{
						echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
						unset($_SESSION['msg']['login-err']);
					}
				?>
				
				<label class="grey" for="username">Username:</label>
				<input class="field" type="text" name="username" id="username" value="" size="23" />
				<label class="grey" for="password">Password:</label>
				<input class="field" type="password" name="password" id="password" size="23" />
            	<label><input name="rememberMe" id="rememberMe" type="checkbox" checked="checked" value="1" /> &nbsp;Remember me</label>
    			<div class="clear"></div>
				<input type="submit" name="submit" value="Login" class="bt_login" />
			</form>
		</div>
		<div class="left right">			
			<!-- Register Form -->
			<form action="" method="post">
				<h1>Not a member yet? Sign Up!</h1>		
                
                <?php
					
					if($_SESSION['msg']['reg-err'])
					{
						echo '<div class="err">'.$_SESSION['msg']['reg-err'].'</div>';
						unset($_SESSION['msg']['reg-err']);
					}
					
					if($_SESSION['msg']['reg-success'])
					{
						echo '<div class="success">'.$_SESSION['msg']['reg-success'].'</div>';
						unset($_SESSION['msg']['reg-success']);
					}
				?>
                		
				<label class="grey" for="username">Username:</label>
				<input class="field" type="text" name="username" id="username" value="" size="23" />
				<label class="grey" for="email">Email:</label>
				<input class="field" type="text" name="email" id="email" size="23" />
				<label>A password will be sent to your email address provided.</label>
				<input type="submit" name="submit" value="Register" class="bt_register" />
			</form>
		</div>
        
        <?php
		
		else:
		
		?>
        
        <div class="left">
        <?php
		$username = mysql_real_escape_string($_SESSION["user"]);
		echo "<p>" . $row['money'] . "<p>";
		echo $username;
        echo '<h1>'.$_SESSION['user'].'s User Control Panel</h1>';
		echo $money;
        echo '<p><b><font color="#FF0000">IP Address</font></b>: <font color="#FFFFFF">'.$_SERVER['REMOTE_ADDR'].'</font></p>';
        ?>
        <a href="?logoff">Log out</a>
        </div>
        
        <div class="left right">
		<h1>Account Settings</h1>
        </div>
        
        <?php
		endif;
		?>
	</div>
</div> <!-- /login -->	

<!-- The tab on top -->	
<div class="tab">
	<ul class="login">
    	<li class="left">&nbsp;</li>
        <li>Welcome <?php echo $_SESSION['user'] ? $_SESSION['user'] : 'Guest';?>!</li>
		<li class="sep">|</li>
		<li id="toggle">
			<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In | Register';?></a>
			<a id="close" style="display: none;" class="close" href="#">Close Panel</a>			
		</li>
    	<li class="right">&nbsp;</li>
	</ul> 
</div> <!-- / top -->
[/php]

I might be doing something wrong, but I’ve been trying for hours now and can’t seem to work out how php works with mysql, seems like it does what it wants.

Update: I have realised what you meant about reading and echoing the database rows, fixed that, cheers man!
Just the username part now.

I don’t see where you updated the code? Re-read my post again, you want to replace your current username validation code with mine.

I have this for the registration part of the script:

[php]else if($_POST[‘submit’]==‘Register’)
{
// If the Register form has been submitted
$err = array();

if(strlen($_POST['username'])< 9 || strlen($_POST['username'])> 18)
{
	$err[]='Your username must be between 9 and 18 characters.';
}

if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username']))
{
	$err[]='Your username contains invalid characters.';
}

if(!checkEmail($_POST['email']))
{
	$err[]='Your email address is not valid.';
}

if(!count($err))
{
	// If there are no errors
	
	$pass = substr(sha1($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6);
	// Generate a random password
	
	$_POST['email'] = mysql_real_escape_string($_POST['email']);
	$_POST['username'] = mysql_real_escape_string($_POST['username']);
	// Escape the input data
	
	
	mysql_query("	INSERT INTO playerdata(user,password,level,money,email,ip,datetime)
					VALUES(
					
						'".$_POST['username']."',
						'".sha1($pass)."',
						'1',
						'20',
						'".$_POST['email']."',
						'".$_SERVER['REMOTE_ADDR']."',
						NOW()
						
					)");
	
	if(mysql_affected_rows($link)== 1)
	{
		send_mail(	'[email protected]',
					$_POST['email'],
					'Welcome to Domination Roleplay.',
					'Your password is: '.$pass);

		$_SESSION['msg']['reg-success']='An email has been sent containing your password. '.$pass;
	}
	else $err[]='That username has already been taken.';
}

if(count($err))
{
	$_SESSION['msg']['reg-err'] = implode('<br />',$err);
}	

header("Location: http://127.0.0.1/");
exit;

}[/php]

I have tried replacing:

[php]if(strlen($_POST[‘username’])< 9 || strlen($_POST[‘username’])> 18)
{
$err[]=‘Your username must be between 9 and 18 characters.’;
}

if(preg_match(’/[^a-z0-9-_.]+/i’,$_POST[‘username’]))
{
$err[]=‘Your username contains invalid characters.’;
}[/php]

with:

[php]$usernames = array(

‘JohnAdam’,

‘John_Ada’,

‘Jon_Ada’,

‘Jon_Adam’,

‘John_Adam_’,

‘John_Adam’,

‘John__Adam’,

‘John_Test_Adam’
);

foreach($usernames as $username) {

echo $username . ": " . (preg_match(’/^[A-Za-z0-9]{4,}_{1}[A-Za-z0-9]{4,}$/’, $username) ? “Valid” : “Invalid”) . “\n”;
}[/php]

There’s something I’m doing wrong but not sure what as this code you’ve written is way too advanced for me :stuck_out_tongue:
Cheers and sorry for the trouble.

That is the wrong code to use in your script. That code is simply to demonstrate that it works.

I think you missed where I said to replace it with this:

[php]
if (!preg_match(’/^[A-Za-z]{4,9}_{1}[A-Za-z]{4,9}$/’, $_POST[‘username’])) {
$err[] = ‘Your username is invalid.’;
}
[/php]

I would like to thank you so much, I haven’t slept for around 5 days due to constant web designing and PAWNO scripting (for GTA San Andreas Multiplayer) so I kind of missed your explanation above, finally got it working and you are a legend. +rep.

How do I add +1 to your karma? Thanks again.

You should be able to see a + / - under his name by his posts, just hit the +.

Sponsor our Newsletter | Privacy Policy | Terms of Service