Check Username

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
justinccagle
Forum Newbie
Posts: 3
Joined: Mon Sep 27, 2010 6:27 pm

Check Username

Post by justinccagle »

Hello I'm a noob to php and mysql I have written a script for a registration page and login page. The registration and login portions work fine but now I'm try to check to see if the user name already exist to display an error if so. I have tried several ways and checked several forums for the answer but nothing has worked. I would appreciate any help possible below is my registration script.

Justin Cagle :banghead:

<?php
$con = mysql_connect("localhost","*removed*","*removed*");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("users", $con);

$sql="INSERT INTO users (name, email, username, password)
VALUES
('$_POST[name]','$_POST[email]','$_POST[username]','$_POST[password]')";

if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";

mysql_close($con)
?>
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Check Username

Post by califdon »

I'm not sure where to start. The script you showed is intended to insert a new record into a table, not check on whether data submitted matches what is in the table. You need to study a very basic SQL tutorial. Trying things at random isn't an efficient way to learn a precise skill like programming. When you reach the point where you're at least in the ballpark, post your entire script, which I don't think you did here, because there is no place where you obtain the username and password to search for. Finally, when you do post a script, please enclose the script in PHP Code tags so that it is easier to read. Just click the PHP Code button above the box where you enter your post.
justinccagle
Forum Newbie
Posts: 3
Joined: Mon Sep 27, 2010 6:27 pm

Re: Check Username

Post by justinccagle »

This is the jist of what I'm trying to achieve, the form is a html form that links to register.php through the form action feature.

Code: Select all

 
<?php

mysql_connect("localhost", "*removed*", "*removed*") or die(mysql_error());

mysql_select_db("users") or die(mysql_error());;

 

$name = $_POST["name"];

$email = $_POST["email"];

$username = $_POST["username"];

$password = $_POST["password"];

//above values are taken from form on previous page...

//first name, last name, username, password and email

 

$subject = "Thankyou for registering with Grafax!";

$from = "";

$message = 'You have just registered the following details at Grafax.co.uk:<hr/>

<table bgcolor="#E0E0E0">

<strong>First Name: </strong>'. $fname .'<br/>

<strong>Username: </strong>'. $username .'<br/>

<strong>Password: </strong>'. $password .'</table>

<hr/>

<h3><a href="#login.html">Click here to login</a></h3>';

 

 

//this is where i tried to check the username against whats in the database.

//If $uname entered by user is different to the result from the mysql query

//then insert information. it didnt work.... :P

$dbunames = mysql_query("SELECT * FROM users WHERE username='$username'");

if ($username != $dbunames)

 

 

{

mysql_query("INSERT INTO users (`name`, `username`, `password`, `email`) VALUES ('$name', '$username', '$password', '$email')");

mail($email,$subject,$message,"From:$from\r\nReply-to: $from\r\nContent-type: text/html; charset=us-ascii");

echo "<h1>Successfully added: </h1><br><h3>name:</h3>";

echo $name;

echo "<br /><h3>username:</h3>";

echo $username;

echo "<br /><h3>password:</h3>";

echo $password;

echo "<hr>";

echo "<h1>Email sent to ". $email ."</h1>";

}

else

{

echo "Username taken.";

}

?>
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Check Username

Post by califdon »

OK, first, is that really what you want to do, any time anybody submits anything that doesn't match a username already in the database, insert a new record?? Someone could fill up your database with junk, and any time someone makes a typo when they enter their username, you create a new record? Doesn't sound like a good plan to me. Ordinarily, you would check to see if there's a match and if there's not, redirect to a page that asks the user if they want to open a new account.

Then, you have several critical omissions in your query code. Your variable $dbunames is not a simple variable, it is a "resource", which means that your code must either fetch rows from the resource and then examine the row array to get to the data itself, or you can check the number of rows returned in the resource to know whether or not there was a match. It must look something like this:

Code: Select all

$dbunames = mysql_query("SELECT * FROM users WHERE username='$username'");
if(mysql_num_rows($dbunames) > 0)
{
   // there was a match, so redirect to the authorized page, or whatever
} else {
   // there was no match, so redirect to another page, 
   // determine whether the user wants to open a new account, if so, 
   // THEN proceed with your insertion
}
Then you are using raw input from the html form as input to your database, a highly dangerous practice. I could enter some simple code into the "name" or "password" form input and gain access to all your data or delete all your data! There's a lot written about this "SQL injection" -- Google that term. You must always screen or "cleanse" input from html forms.
kcjonez
Forum Newbie
Posts: 8
Joined: Mon Sep 27, 2010 12:51 pm

Re: Check Username

Post by kcjonez »

another unecessary practice I see in there is assigning values to $name, $password, etc.

Just creates extra code that you can simply get by calling the $_POST[''] values.

Try this code for your registration page. Just copy and paste it to a new file on your server.

Code: Select all

<?
mysql_connect("localhost", "*removed*", "*removed*") or die(mysql_error());

mysql_select_db("users") or die(mysql_error());

//  This clears the notices
$usrnotice = "";
$passnotice = "";


//  Checks if the form has been submitted
if ( isset ( $_POST['submit'] ) && $_POST['submit'] == "submit" ) {
	//  Check that the username has not been used already
	$chkusr = @mysql_query("SELECT * FROM `users` WHERE `username` = '" . $_POST['username'] . "'") or die(mysql_error());
		if ( mysql_num_rows($chkusr) > 0 ) {
			$usrnotice = "The Username: " . $_POST['username'] . " has already been chosen.  Please select another.";
		} elseif ( $_POST['password'] != $_POST['verpass'] ) {
		$passnotice = "Your passwords do not match.";
	} else {
		//  All is good!  Enter into the database!
		@mysql_query("INSERT INTO `users` (
`name` ,
`username` ,
`password` ,
`email`
)
VALUES (
'" . $_POST['name'] . "', '" . $_POST['username'] . "', '" . $_POST['password'] . "', '" . $_POST['email'] . "')") or die(mysql_error());
	//  Note: you can encrypt the password several ways, one way I like to use is MD5
	//  Change the password value to MD5('" . $_POST['password'] . "') to encrypt it
	
		//  Redirects to thanks.php and stops the script
		header("Location: thanks.php");
		die();
	}
}


?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Register</title>
</head>

<body>
<form action="<? echo $_SERVER['PHP_SELF']; ?>" name="register" method="post">
					<table border="0" align="center" cellpadding="2" cellspacing="2">
                      <tr>
                        <td align="right" valign="middle">Name:&nbsp; </td>
                        <td align="center"><input name="name" type="text" class="menuheader" id="name" value="<? echo $_POST['name']; ?>" size="25" /></td>
                      </tr>
		<?
			if ( isset ( $usrnotice ) && $usrnotice != "" ) {
			?>
                      <tr>
                        <td colspan="2" align="right" valign="middle"><? echo $usrnotice; ?></span></td>
                      </tr>
		<?
		}
		?>
                      <tr>
                        <td align="right" valign="middle">Username:&nbsp; </td>
                        <td align="center"><input name="username" type="text" id="username" value="<? echo $_POST['username']; ?>" size="25" /></td>
                      </tr>
                      <tr>
                        <td align="right" valign="middle">Password:&nbsp; </td>
                        <td align="center"><input name="password" type="password" id="password" size="25" maxlength="12" /></td>
                      </tr>
		<?
			if ( isset ( $passnotice ) && $passnotice != "" ) {
		?>
                      <tr>
                        <td colspan="2" align="right" valign="middle"><? echo $passnotice; ?></td>
                      </tr>
		<?
		}
		?>
                      <tr>
                        <td align="right" valign="middle">Verify Password:&nbsp; </td>
                        <td align="center"><input name="verpass" type="password" id="verpass" size="25" maxlength="12" /></td>
                      </tr>
                      <tr>
                        <td align="right" valign="middle">Email Address:&nbsp; </td>
                        <td align="center"><input name="email" type="text" id="email" value="<? echo $_POST['email']; ?>" size="25" /></td>
                      </tr>
                      <tr>
                        <td colspan="2" align="center"> <input name="submit" type="submit" id="submit" value="submit" />                        </td>
                      </tr>
                    </table>
</form>
</body>
</html>
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: Check Username

Post by John Cartwright »

Please do not post live username/passwords (I've removed them). Thanks.
kcjonez
Forum Newbie
Posts: 8
Joined: Mon Sep 27, 2010 12:51 pm

Re: Check Username

Post by kcjonez »

John Cartwright wrote:Please do not post live username/passwords (I've removed them). Thanks.
sorry...was just posting what he posted initially. Might wanna check up ^^^ there too.
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: Check Username

Post by twinedev »

It is good to get into the practice of separating the logic/presentation of the code as in kcjonez's example. As you can see, it makes it easier to see what is going on.

A few things I would change in his code, using full PHP opening tags <?php instead of short ones. Just good practice to get into as many servers do not support the short form by default. (I'll be the first to admit, I really REALLY miss <?= $strVariable; ?> lol) At work we have to program sites to be able to be moved off to the client's preferred server if they choose to leave.

The other is I would use the exit(); statement instead of die(); after the header redirect. This is my own personal preference, but I tend to save die() for things that shouldn't hit (ie, the first two mysql statements). IMO helps when scanning through the code see the difference between something that is a "should end" compared to "oh crap it broke and ended" ;-)

Also as mentioned, clense anything that is submited or controlled by the user, $_POST variables.

Code: Select all

$SQL = sprintf("INSERT INTO `users` (`name`, `username`, `password`, `email`) VALUES ('%s' ,'%s', MD5('%s'), '%s')",
                mysql_real_escape_string($_POST['name']),
                mysql_real_escape_string($_POST['username']),
                mysql_real_escape_string($_POST['password']),
                mysql_real_escape_string($_POST['email']) );

mysql_query($SQL) or die(mysql_error());
Lastly, I would suggest using $_SERVER['REQUEST_URI'] instead of $_SERVER['PHP_SELF'] as this does have the possibility to open you up to XSS attacks.

Just some tips I think that are good to get started with early ;-)

-Greg
kcjonez
Forum Newbie
Posts: 8
Joined: Mon Sep 27, 2010 12:51 pm

Re: Check Username

Post by kcjonez »

yes...I tend to get a little lazy and put die() for everything stopping the script.

exit() should be used for cleaner code.

Never tried the mysql_real_escape_string...does that purge the $_POST values?
justinccagle
Forum Newbie
Posts: 3
Joined: Mon Sep 27, 2010 6:27 pm

Re: Check Username

Post by justinccagle »

i have worked out the problem with some of your suggestions. Thank you so much for the advice. :mrgreen:
Post Reply