problems with a login/register script

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

cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

problems with a login/register script

Post by cwheel3915 »

I have two scripts for a login im making, the only trouble is I keeo getting errors on both, once I solve one I get another. So I wanted some more experienced people to take a look, and see if they knew what was going on.

Code: Select all

<?php

session_start(); 
$email = addslashes($_POST['email']); //protect again mysql injection
$_POST['password'] = addslashes($_POST['password']); //same
$_POST['password2'] = addslashes($_POST['password2']); //same again

$checkemail = mysql_query("SELECT 'email' FROM 'userdb' "
. "WHERE 'email' = ' " . $_POST['email'] . " ' ", $mysql);

if(mysql_num_rows($checkemail) == "1") {
	echo <<<TAKEN
	That user name has already been taken
	TAKEN;
	include "register.php";
	exit; }
	


if(strlen('$_POST[email]' > 32)){
	echo "Username is too long";
	include "register.php";
	exit;
	      }
	
	if($_POST'[password]' != $_POST'[password2]'){
		echo "The passwords entered do not match, try again.";
		include "register.php";
		exit; }  
		
          $password = md5($_POST'[password]');
	mysql_query("INSERT INTO 'userdb' ('username' . 'password') "
	. "VALUES (' " . $email . " ' , ' " . $password . " ')" , $mysql);
	
	echo "account created successfully <a href="index.php">Click here to return to login page.</a>"; 
	
	?>
this is the script that adds users to the database I keed getting a $end error on it.



This next code, is the script to check if a persons name exist in the database, and the password matches. If so login.


Code: Select all

<?php

session_start();
include "mysql.inc.php";
$_POST['email'] = addslashes($_POST['email']); //protects agian mysql injection
$_POST['password'] = addslashes($_POST['password']); //same as above
$password = md5($_POST['password']); //encrypt the password
$userrow = mysql_query("SELECT * FROM 'userdb' " . " WHERE 'email' = ' " $_POST['email'] . " ' " 
. " & $password . " ';",$mysql);

if(mysql_num_rows($userrow) != "1"){

//no rows found, wrong password or username

echo "<a href="index.php">Click here to return to login page</a>"

	
} else {
	
	//1 row exactly found, this user is valid start session, and take to main page
	
	$_SESSION['user'] = $_POST['email'];
	
	header("location: main.php");
}

?>
On this one im getting all kinds of errors, I fix one then another.
jraede
Forum Contributor
Posts: 254
Joined: Tue Feb 16, 2010 5:39 pm

Re: problems with a login/register script

Post by jraede »

Well, in your first script, make sure you enclose your echo strings with " or '. From a quick glance, I can't see what else is wrong with it. Other than that, it would help if you posted exactly what errors you are getting.
cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

Re: problems with a login/register script

Post by cwheel3915 »

Alright, I fixed the $end error, by fixing the echos, I now have the following getting theses errors.

Warning: mysql_query() expects parameter 2 to be resource, null given in C:\xampp\htdocs\mafiagame\adduser.php on line 9

Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\xampp\htdocs\mafiagame\adduser.php on line 11
The passwords entered do not match, try again.


Code: Select all


<?php

session_start(); 
$email = addslashes($_POST['email']); //protect again mysql injection
$_POST['password'] = addslashes($_POST['password']); //same
$_POST['password2'] = addslashes($_POST['password2']); //same again

$checkemail = mysql_query("SELECT 'email' FROM 'userdb' "
. "WHERE 'email' = ' " . $_POST['email'] . " ' ", $mysql);

if(mysql_num_rows($checkemail) == "1") 
{
	echo "that name is already taken";
       include "register.php";
	exit; 
	
	}
	
	


if(strlen($_POST['email'] > 32))

{
	echo "Username is too long";
	include "register.php";
	exit;
	      
	}
	
	
	if($_POST['password'] != $_POST['password2'])
	{
		echo "The passwords entered do not match, try again.";
		include "register.php";
		exit; 
		
		}
		
		
		
	$password = md5($_POST['password']);
	mysql_query("INSERT INTO 'userdb' ('username' . 'password') "
	. "VALUES (' " . $email . " ' , ' " . $password . " ')" , $mysql);
	
	echo "account created successfully <a href=\"index.php\">Click here to return to login page.</a>"; 
	
	
	?>
 



In the second code I listed I get this error.


Parse error: syntax error, unexpected T_VARIABLE in C:\xampp\htdocs\mafiagame\checkpass.php on line 8
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: problems with a login/register script

Post by flying_circus »

There are alot of "issues" with your code. User security is extremely important, make sure you understand what you are doing before you begin accepting user accounts. I've made some changes to your code. These changes aren't necessarily adequate, they are a step forward. If you have questions about what I've done, post back up.

Code: Select all

<?php
  # Begin Session
    session_start();
    
  # If Magic Quotes are enabled, stripslashes()
    if(get_magic_quotes_gpc()) {
      $input = array(&$_GET, &$_POST, &$_COOKIE, &$_ENV, &$_SERVER);
      
      while(list($k, $v) = each($input)) {
        foreach($v as $key => $val) {
          if(!is_array($val)) {
            $input[$k][$key] = stripslashes($val);
            continue;
          }
          $input[] =& $input[$k][$key];
        }
      }
      unset($input);
    }
    
  # Fetch POST Vars
  /* Check for existence before referencing a variable! */
  /* Adding slashes does NOT protect you from SQL Injection.  Use: mysql_real_escape_string() */
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    $password = isset($_POST['password']) ? $_POST['password']: '';
    $password2 = isset($_POST['password2']) ? $_POST['password2'] : '';
    
  # Sanity Check
  /* strlen() is not accurate for multibyte characters.  Make sure your character set is not multibyte, else use mb_strlen() */
  /* Verify that $email is not empty and meets minimum length requirements */
  /* A Max length of 32 is pretty short for an email address */
    if(strlen($email < 3)) {
      echo "Email is too short";
      include "register.php";
      exit;
    }
    
    if(strlen($email > 32)) {
      echo "Email is too long";
      include "register.php";
      exit;
    }
    
    if($password !== $password2) {
      echo "The passwords entered do not match, try again.";
      include "register.php";
      exit;
    }
    
  # Connect to the MySql Database
  /* You need to connect to the database before you can access it */
    $mysql = mysql_connect('my_server', 'my_password', 'my_password');
    
  # Select Database to use
    mysql_selectdb('my_database');
    
  # Check if email already exists
    # Build MySql Query
      $querystring = sprintf("SELECT `email` FROM `userdb` WHERE `email` = '%s';",
                             mysql_real_escape_string($email, $mysql));
                             
    # Execute MySql Query
      $query = mysql_query($querystring, $mysql);
      
    # Results MySql Query
    /* Check for results greater than 0.  If you have duplicates, then your system would allow more duplicates. */
      if(mysql_num_rows($query) > 0) {
        echo "that name is already taken";
        include "register.php";
        exit;
      }
      
  # Create new User in the database
  /* md5 is no longer cryptographically suitable for password hashing.  Use sha256 at the very least */
    # Destroy $password2
      unset($password2);
      
    # Hash $password
      $password = hash('sha512', $password);
      
    # Build MySql Query
      $querystring = sprintf("INSERT INTO `userdb` (`email`, `password`) VALUES ('%s', '%s');",
                             mysql_real_escape_string($email, $mysql),
                             mysql_real_escape_string($password, $mysql));
                             
    # Execute MySql Query
      if(mysql_query($querystring, $mysql)) {
      # Results MySql Query
        echo "account created successfully <a href=\"index.php\">Click here to return to login page.</a>";
      } else {
        echo "Your account could not be created.  Please contact the system administrator.";
      }
?>
cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

Re: problems with a login/register script

Post by cwheel3915 »

I do have one question.

Do you know of some up to date language books? I have tried several, but they always seem to be outdated, and the code never works without me tweaking it.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: problems with a login/register script

Post by flying_circus »

Which part do you want to study?

The PHP documentation is a great resource. A bit bland to read from start to finish, but between the code examples and some user comments, its invaluable.

If you want a good intro to php security, pick up PHP Architects | Guide to PHP Security by Ilia.

owasp is also a good resource as well.
cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

Re: problems with a login/register script

Post by cwheel3915 »

Code: Select all


<?php
  # Begin Session
    session_start();
    
  # If Magic Quotes are enabled, stripslashes()
    if(get_magic_quotes_gpc()) {
      $input = array(&$_GET, &$_POST, &$_COOKIE, &$_ENV, &$_SERVER);
      
      while(list($k, $v) = each($input)) {
        foreach($v as $key => $val) {
          if(!is_array($val)) {
            $input[$k][$key] = stripslashes($val);
            continue;
          }
          $input[] =& $input[$k][$key];
        }
      }
      unset($input);
    }
    
  # Fetch POST Vars
  /* Check for existence before referencing a variable! */
  /* Adding slashes does NOT protect you from SQL Injection.  Use: mysql_real_escape_string() */
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    $password = isset($_POST['password']) ? $_POST['password']: '';
    $password2 = isset($_POST['password2']) ? $_POST['password2'] : '';
    
  # Sanity Check
  /* strlen() is not accurate for multibyte characters.  Make sure your character set is not multibyte, else use mb_strlen() */
  /* Verify that $email is not empty and meets minimum length requirements */
  /* A Max length of 32 is pretty short for an email address */
    if(strlen($email < 3)) {
      echo "Email is too short";
      include "register.php";
      exit;
    }
    
    if(strlen($email > 32)) {
      echo "Email is too long";
      include "register.php";
      exit;
    }
    
    if($password !== $password2) {
      echo "The passwords entered do not match, try again.";
      include "register.php";
      exit;
    }
    
  # Connect to the MySql Database
  /* You need to connect to the database before you can access it */
    $mysql = mysql_connect('my_server', 'my_password', 'my_password');
    
  # Select Database to use
    mysql_selectdb('my_database');
    
  # Check if email already exists
    # Build MySql Query
      $querystring = sprintf("SELECT `email` FROM `userdb` WHERE `email` = '%s';",
                             mysql_real_escape_string($email, $mysql));
                             
    # Execute MySql Query
      $query = mysql_query($querystring, $mysql);
      
    # Results MySql Query
    /* Check for results greater than 0.  If you have duplicates, then your system would allow more duplicates. */
      if(mysql_num_rows($query) > 0) {
        echo "that name is already taken";
        include "register.php";
        exit;
      }
      
  # Create new User in the database
  /* md5 is no longer cryptographically suitable for password hashing.  Use sha256 at the very least */
    # Destroy $password2
      unset($password2);
      
    # Hash $password
      $password = hash('sha512', $password);
      
    # Build MySql Query
      $querystring = sprintf("INSERT INTO `userdb` (`email`, `password`) VALUES ('%s', '%s');",
                             mysql_real_escape_string($email, $mysql),
                             mysql_real_escape_string($password, $mysql));
                             
    # Execute MySql Query
      if(mysql_query($querystring, $mysql)) {
      # Results MySql Query
        echo "account created successfully <a href=\"index.php\">Click here to return to login page.</a>";
      } else {
        echo "Your account could not be created.  Please contact the system administrator.";
      }
?>

Alright this code works kinda, except it appears that for some reason the $_POST variables are not making from the register.php to the adduser.php No matter what is entered in the email space on the Register.php the adduser.php still comes back saying that the email is too short.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: problems with a login/register script

Post by flying_circus »

can you post your register.php? I'm most interested in your form.
cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

Re: problems with a login/register script

Post by cwheel3915 »

Certainly this is the register.php

Code: Select all

<html>
<head>

<title>Test register page</title>


<link rel="stylesheet" type="text/css" href="test.css" />

</head>

<body>




<div class="main">

<center><br/><Div class="form">
<form action="adduser.php" method="POST" />

Email:<br/><Input type="text" size = "15" maxlength="55" name="email" /><br/>


Password:<br/>
<input type="password" size="15" maxlength="12" name="password"  /><br/>

Confirm password:<br/>
<input type="password" size="15" maxlength="12" name="password2"  /><br/> 




<br/><br/>
<input type="submit" value="Submit" />


</form></center>



</div>



</div>


<div class="header">
<center><h2>Whater.whater.com</h2></center>


</div>







</body>

</html>
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: problems with a login/register script

Post by flying_circus »

I haven't tested this on my devbox, but I noticed this line:

Code: Select all

<form action="adduser.php" method="POST" />
You are opening and closing the form tag with 1 line. Try removing the trailing slash to make it look like:

Code: Select all

<form action="adduser.php" method="post">

Your code that I modified:

Code: Select all

<html>
  <head>
    <title>Test register page</title>
    <link rel="stylesheet" type="text/css" href="test.css" />
  </head>
  <body>
    <div class="main">
      <center>
        <br />
        <div class="form">
          <form action="adduser.php" method="post">
            Email:<br /><input type="text" size = "15" maxlength="55" name="email" /><br />
            Password:<br /><input type="password" size="15" maxlength="12" name="password"  /><br />
            Confirm password:<br /><input type="password" size="15" maxlength="12" name="password2"  /><br />
            <br /><br />
            <input type="submit" value="Submit" />
          </form>
        </div>
      </center>
    </div>
    <div class="header">
      <center><h2>Whater.whater.com</h2></center>
    </div>
  </body>
</html>
cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

Re: problems with a login/register script

Post by cwheel3915 »

Its still flagging the Email is too short, no matter how many characters are in the field.

Thats the full register, and addusers pages.. I just cant figure out why the variables are seemingly not passing.
cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

Re: problems with a login/register script

Post by cwheel3915 »

Okay, I just checked I added echo "$email" after the script got the $_post and the email was displayed, so it is getting the variable.

And in that case something else is causing the email too short to be flagged, but I just cant figure out what,
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: problems with a login/register script

Post by flying_circus »

Aha! Found a syntax error

Code: Select all

if(strlen($email < 3)) { 
should have been:

Code: Select all

if(strlen($email) < 3) { 


Try this:

Code: Select all

<?php
  # Begin Session
    session_start();
    
  # If Magic Quotes are enabled, stripslashes()
    if(get_magic_quotes_gpc()) {
      $input = array(&$_GET, &$_POST, &$_COOKIE, &$_ENV, &$_SERVER);
      
      while(list($k, $v) = each($input)) {
        foreach($v as $key => $val) {
          if(!is_array($val)) {
            $input[$k][$key] = stripslashes($val);
            continue;
          }
          $input[] =& $input[$k][$key];
        }
      }
      unset($input);
    }
    
  # Fetch POST Vars
  /* Check for existence before referencing a variable! */
  /* Adding slashes does NOT protect you from SQL Injection.  Use: mysql_real_escape_string() */
    $email = isset($_POST['email']) ? $_POST['email'] : '';
    $password = isset($_POST['password']) ? $_POST['password']: '';
    $password2 = isset($_POST['password2']) ? $_POST['password2'] : '';
    
  # Sanity Check
  /* strlen() is not accurate for multibyte characters.  Make sure your character set is not multibyte, else use mb_strlen() */
  /* Verify that $email is not empty and meets minimum length requirements */
  /* A Max length of 32 is pretty short for an email address */
    if(strlen($email) < 3) {
      echo "Email is too short";
      include "register.php";
      exit;
    }
    
    if(strlen($email) > 32) {
      echo "Email is too long";
      include "register.php";
      exit;
    }
    
    if($password !== $password2) {
      echo "The passwords entered do not match, try again.";
      include "register.php";
      exit;
    }
    
  # Connect to the MySql Database
  /* You need to connect to the database before you can access it */
    $mysql = mysql_connect('my_server', 'my_password', 'my_password');
    
  # Select Database to use
    mysql_selectdb('my_database');
    
  # Check if email already exists
    # Build MySql Query
      $querystring = sprintf("SELECT `email` FROM `userdb` WHERE `email` = '%s';",
                             mysql_real_escape_string($email, $mysql));
                             
    # Execute MySql Query
      $query = mysql_query($querystring, $mysql);
      
    # Results MySql Query
    /* Check for results greater than 0.  If you have duplicates, then your system would allow more duplicates. */
      if(mysql_num_rows($query) > 0) {
        echo "that name is already taken";
        include "register.php";
        exit;
      }
      
  # Create new User in the database
  /* md5 is no longer cryptographically suitable for password hashing.  Use sha256 at the very least */
    # Destroy $password2
      unset($password2);
      
    # Hash $password
      $password = hash('sha512', $password);
      
    # Build MySql Query
      $querystring = sprintf("INSERT INTO `userdb` (`email`, `password`) VALUES ('%s', '%s');",
                             mysql_real_escape_string($email, $mysql),
                             mysql_real_escape_string($password, $mysql));
                             
    # Execute MySql Query
      if(mysql_query($querystring, $mysql)) {
      # Results MySql Query
        echo "account created successfully <a href=\"index.php\">Click here to return to login page.</a>";
      } else {
        echo "Your account could not be created.  Please contact the system administrator.";
      }
?>
cwheel3915
Forum Commoner
Posts: 28
Joined: Wed Apr 28, 2010 8:02 pm

Re: problems with a login/register script

Post by cwheel3915 »

That fixed the issue with the email check not working right, but now im recieving this error.

Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\mafiagame\adduser.php on line 70
Your account could not be created. Please contact the system administrator


I appreciate all the help, I obviously need to study more on syntax.
User avatar
flying_circus
Forum Regular
Posts: 732
Joined: Wed Mar 05, 2008 10:23 pm
Location: Sunriver, OR

Re: problems with a login/register script

Post by flying_circus »

It means that there is a problem with the query, while checking username existence.

You'll have to verify that the code matches whats in your database. Check to make sure the field and table names are correct.

Have you already set up your database and put your login credentials into the code I've posted? That is information that I'm not certain of, so I just put placeholders.
Post Reply