SitePoint Sponsor

User Tag List

Results 1 to 11 of 11
  1. #1
    SitePoint Zealot
    Join Date
    May 2010
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    User registration code driving me nuts

    My user rego code:

    Code:
    <?php
    if (isset($_POST['register'])) {
    	require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php';
    		$username = mysqli_real_escape_string($link, $_POST['username']);
    		$email = mysqli_real_escape_string($link, $_POST['email']);
    		$emailmatch = mysqli_real_escape_string($link, $_POST['emailmatch']);
    		$password = mysqli_real_escape_string($link, $_POST['password']);
    		$passwordmatch = mysqli_real_escape_string($link, $_POST['passwordmatch']);
    			if (empty($username) || empty($email) || empty($emailmatch) || empty($password) || empty($passwordmatch)) { $errorempty = '1'; }
    			else
    				if (strlen($username) < 2 || strlen($username) > 25) { $errorusername = '1'; }
    			else
    				if (strlen($password) < 3 || strlen($password) > 55) { $errorpassword = '1'; }
    			else
    				if (strlen($email) < 3 || strlen($email) > 55) { $erroremail = '1'; }
    			else
    				if ($password != $passwordmatch) { $errorpasswordmatch = '1'; }
    			else
    				if ($email != $emailmatch) { $erroremailmatch = '1';}
    			else
    				if (!empty($username) && !empty($email) && !empty($emailmatch) && !empty($password) && !empty($passwordmatch)) {
    				
    							$checkuser = mysqli_query($link, "SELECT username FROM members WHERE username = '$username'");
    								$result_user = mysqli_num_rows($checkuser);
    									if ($result_user > 0) { $errorusernametaken = '1'; }
    									
    							$checkemail = mysqli_query($link, "SELECT email FROM members WHERE email = '$email'");
    								$result_email = mysqli_num_rows($checkemail);
    									if ($result_email > 0) { $erroremailtaken = '1'; }
    									}
    									
    									else
    									
    									$mix = md5($password . 'salt');
    									$sql = "INSERT INTO members SET username = '$regusername', email = '$regemail', password = '$mix'";
    										if (!mysqli_query($link, $sql)) {
    											$error = 'Error: ' . mysqli_error($link);
    											include 'error.php';
    											}
    								else {include 'success.php'; exit(); }
    }
    ?>
    Everything works fine except one thing when the user actually succeeds in registering - the user actually gets put in the database if that is the case.. but the password isn't being put in:

    Code:
    'Notice: Undefined variable: mix in register.php on line 43'
    I have finally got everything else working so that errors show up for the correct reason, and you can only register if the username and/or email isn't taken etc.

    I have been re-arranging and trying new things in this code all day long, and I'd love some help.

    Feel free to tell me if my code sucks in general, I'm just learning. Sorry for the ugly formatting :P

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    See how this goes for you

    PHP Code:
    <?php

    function error($message$use_file=false) {
        if (!
    $use_file) {
            die(
    $message '<br /><br /><a href="javascript:history.go(-1)">Go back</a>');
        } else {
            
    $error $message;
            include 
    'error.php';
        }
    }

    if (isset(
    $_POST['register'])) {
        require_once 
    $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php';
        
        
    $regex '/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)$/i';
        
        if ((!isset(
    $_POST['username']) || !isset($_POST['email']) || !isset($_POST['emailmatch']) || !isset($_POST['password']) || !isset($_POST['passwordmatch'])) ||
            (empty(
    $_POST['username']) || empty($_POST['email']) || empty($_POST['emailmatch']) || empty($_POST['password']) || empty($_POST['passwordmatch']))) {
            
    error('One or more fields are invalid, please make sure all fields have a value!');
        }
        
        
    $username mysqli_real_escape_string($link$_POST['username']);
        
    $email mysqli_real_escape_string($link$_POST['email']);
        
    $emailmatch mysqli_real_escape_string($link$_POST['emailmatch']);
        
    $password mysqli_real_escape_string($link$_POST['password']);
        
    $passwordmatch mysqli_real_escape_string($link$_POST['passwordmatch']);
        
        if (
    strlen($username) < || strlen($username) > 25) {
            
    error('The username you have entered is invalid, please make sure its 2 - 25 characters long!');
        } else if (
    strlen($password) < || strlen($password) > 55) {
            
    error('The password you have entered is invalid, please make sure its 3 - 55 characters long!');
        } else if (!
    preg_match($regex$email)) {
            
    error('The email address you entered is invalid!');
        } else if (
    $email != $emailmatch) {
            
    error('The confirmation email address you entered does NOT match the first email address!');
        } else if (
    $password != $passwordmatch) {
            
    error('The confirmation password you entered does NOT match the first password!');
        }

        
    $result mysqli_query($link"SELECT username FROM members WHERE username = '$username'");
        
    $user_numrows mysqli_num_rows($result);
        
    mysqli_free_result($result);
        
        if (
    $user_numrows 0) {
            
    error('Sorry but the username you have chosen is already in use, please try another username!');
        }

        
    $result mysqli_query($link"SELECT email FROM members WHERE email = '$email'");
        
    $email_numrows mysqli_num_rows($result);
        
    mysqli_free_result($result);
        
        if (
    $email_numrows 0) {
            
    error('Sorry but the email you have entered is already in use, please try another email address!');
        }
        
        if (!
    mysqli_query($link"INSERT INTO members SET username = '$username', email = '$email', password = '" md5($password 'salt') . "'")) {
            
    $error 'Error: ' mysqli_error($link);
            
    error($errortrue);
        } else {
            include 
    'success.php';
        }
    }

    ?>

  3. #3
    SitePoint Zealot
    Join Date
    May 2010
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Works great, thank you!

  4. #4
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Your welcome

  5. #5
    SitePoint Zealot
    Join Date
    May 2010
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Or not, and it's a really weird problem.

    the only lines giving me trouble are these:

    Code:
    $mix = md5($password . 'salt');
    $sql = "INSERT INTO members SET username = '$username', email = '$email', password = '$mix'";
    if (!mysqli_query($link, $sql)) {
    $error = 'Error: ' . mysqli_error($link);
    include 'error.php';
    }
    if I change $mix in the query to this, as suggested:

    Code:
    $sql = "INSERT INTO members SET username = '$username', email = '$email', password = '" . md5($password . 'salt') . "'";
    it all works perfectly and I no longer get my original error. but in changing that, I obviously no longer need the first line ($mix =), so I remove it. but when I remove it, I now get THIS error when trying to register:

    Code:
    Notice: Undefined variable: sql in register.php on line 43
    
    Warning: mysqli_query() [function.mysqli-query]: Empty query register.php on line 43
    this just doesn't make any sense to me at all.

  6. #6
    SitePoint Zealot
    Join Date
    May 2010
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok let me start again, here is my ENTIRE register.php

    Code:
    <?php
    session_start();
    if (isset($_SESSION['username'])) {
    	header('Location: /');
    }
    ?>
    <?php
    if (isset($_POST['register'])) {
    	require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php';
    	require_once $_SERVER['DOCUMENT_ROOT'] . '/includes/func.php';
    		$username = mysqli_real_escape_string($link, $_POST['username']);
    		$email = mysqli_real_escape_string($link, $_POST['email']);
    		$emailmatch = mysqli_real_escape_string($link, $_POST['emailmatch']);
    		$password = mysqli_real_escape_string($link, $_POST['password']);
    		$passwordmatch = mysqli_real_escape_string($link, $_POST['passwordmatch']);
    			if (empty($username) || empty($email) || empty($emailmatch) || empty($password) || empty($passwordmatch)) { $errorempty = '1'; }
    			else
    				if (strlen($username) < 2 || strlen($username) > 25) { $errorusername = '1'; }
    			else
    				if (strlen($password) < 3 || strlen($password) > 55) { $errorpassword = '1'; }
    			else
    				if (strlen($email) < 3 || strlen($email) > 55) { $erroremail = '1'; }
    			else
    				if ($password != $passwordmatch) { $errorpasswordmatch = '1'; }
    			else
    				if ($email != $emailmatch) { $erroremailmatch = '1';}
    			else
    				if (!empty($username) && !empty($email) && !empty($emailmatch) && !empty($password) && !empty($passwordmatch)) {
    				
    							$checkuser = mysqli_query($link, "SELECT username FROM members WHERE username = '$username'");
    								$result_user = mysqli_num_rows($checkuser);
    									if ($result_user > 0) { $errorusernametaken = '1'; }
    									
    							$checkemail = mysqli_query($link, "SELECT email FROM members WHERE email = '$email'");
    								$result_email = mysqli_num_rows($checkemail);
    									if ($result_email > 0) { $erroremailtaken = '1'; }
    									}
    									
    									else
    									
    					/* line 42 */				$sql = "INSERT INTO members SET username = '$regusername', email = '$regemail', password = '" . md5($password . 'salt') . "'";
    										if (!mysqli_query($link, $sql)) {
    											$error = 'Error: ' . mysqli_error($link);
    											include 'error.php';
    											}
    								else {include 'success.php'; exit(); }
    }
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    	<title>website</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    	<link href="style1.css" rel="stylesheet" type="text/css"/>
    </head>
    	<body>
    		<div id="wrapper">
    		<div id="main">
    		<div id="register">
    			<form action="" method="post">
    			<center>
    			<?php if (isset($errorempty)) {
    			echo 'Please fill out all required fields.' . '<br/>';
    			}
    			?>
    			</center>
    	Username:<input type="text" name="username"/><?php if (isset($errorusernametaken)) { echo 'Username is in use, please try again' . '<br/>'; } ?><?php if (isset($errorusername)) { echo 'Username must be between 3 and 25 characters.' . '<br/>'; } ?>
    	Your Email:<input type="text" name="email"/><?php if (isset($erroremailtaken)) { echo 'Email is in use, please try again.' . '<br/>'; } ?><?php if (isset($erroremail)) { echo 'Email must be between 3 and 55 characters.' . '<br/>'; } ?>
    	 Email again:<input type="text" name="emailmatch"/><?php if (isset($erroremailmatch)) { echo 'Emails do not match' . '<br/>'; } ?>
    	Password:<input type="password" name="password"/><?php if (isset($errorpassword)) { echo 'Password must be between 3 and 55 characters' . '<br/>'; } ?>
    	Password again:<input type="password" name="passwordmatch"/><?php if (isset($errorpasswordmatch)) { echo 'Passwords do not match.' . '<br/>'; } ?>
    		<input type="submit" name="register" value="Go"/>
    			</form>
    		</div> <!-- end of register -->
    		</div> <!-- end of main -->
    			<?php include $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php'; ?>
    		</div> <!-- end of wrapper -->
    	</body>
    </html>
    So my form+code is all on one page, thus the reason I have created error variables and then checked to see which to display in the form instead of echo+exiting - it would just show a blank page with the error.

    Now... this file works PERFECTLY, provided I have ANYTHING before line 42 as marked... (I could even just put $blah = $bleh. That is what is driving me nuts.

    As soon as I take away the random line I have before the INSERT, it says $SQL is an undefined variable. So for some reason that line is just not being read..?

    There must be a reason why. Any ideas anyone? I want to fix what I have before I add yummy regex stuff etc.. because what I have works, except for this one odd problem!

    Oh and if anyone can tell me how to format my code with colors automatically(?) like sgtlegend did there, I would be grateful to be able to provide better pastes. heh

  7. #7
    SitePoint Zealot
    Join Date
    May 2010
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    or not, all of a sudden it is just inserting into the database everytime, even if I input something that should cause an error.

    I swear I didn't even change anything. Restored the file from my 'yay its working' backup and same thing. Very confused right now. My head is about to explode, I guess I need to rework this entire thing. Really want to be able to do this in one file.

  8. #8
    SitePoint Zealot
    Join Date
    May 2010
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    changed the bottom half of the code to this:

    Code:
    $checkuser = mysqli_query($link, "SELECT username FROM members WHERE username = '$username'");
    $result_user = mysqli_num_rows($checkuser);
    if ($result_user > 0) { $errorusernametaken = '1'; }
    									
    $checkemail = mysqli_query($link, "SELECT email FROM members WHERE email = '$email'");
    $result_email = mysqli_num_rows($checkemail);
    if ($result_email > 0) { $erroremailtaken = '1'; }
    }
    									
    else
    									
    if (!isset($errorempty) && !isset($errorusername) && !isset($errorpassword) && !isset($erroremail) && !isset($errorpasswordmatch) && !isset($erroremailmatch) && !isset($errorusernametaken) && !isset($erroremailtaken)) {
    
    $sql = "INSERT INTO members SET username = '$username', email = '$email', password = '" . md5($password . 'salt') . "'";
    if (!mysqli_query($link, $sql)) {
    $error = 'Error: ' . mysqli_error($link);
    include 'error.php';
    }
    else { include 'success.php'; exit(); }
    }
    and now my errors are displaying correctly, and if there is any error it won't insert the user. but now when there are no errors, the page just refreshes with no execution of the query.

    I really hope someone smarter than me can tell me what I'm doing wrong lol.

  9. #9
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,191
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    I'm confused as i updated your code but you seem to have reverted back to your old code. Try the below as i updated it to set inline errors...

    PHP Code:
    <?php

    if (isset($_POST['register'])) {
        require_once 
    $_SERVER['DOCUMENT_ROOT'] . '/includes/connect.php';
        
        
    $errors false;
        
    $regex '/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[a-z]{2}|aero|asia|biz|cat|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|pro|tel|travel)$/i';
        
        if ((!isset(
    $_POST['username']) || !isset($_POST['email']) || !isset($_POST['emailmatch']) || !isset($_POST['password']) || !isset($_POST['passwordmatch'])) ||
            (empty(
    $_POST['username']) || empty($_POST['email']) || empty($_POST['emailmatch']) || empty($_POST['password']) || empty($_POST['passwordmatch']))) {
            
    $errors true;
        }
        
        if (!
    $errors) {
            
    $username mysqli_real_escape_string($link$_POST['username']);
            
    $email mysqli_real_escape_string($link$_POST['email']);
            
    $emailmatch mysqli_real_escape_string($link$_POST['emailmatch']);
            
    $password mysqli_real_escape_string($link$_POST['password']);
            
    $passwordmatch mysqli_real_escape_string($link$_POST['passwordmatch']);
            
            if (
    strlen($username) < || strlen($username) > 25) {
                
    $errors true;
                
    $usernameError 'The username you have entered is invalid, please make sure its 2 - 25 characters long!';
            } else if (
    strlen($password) < || strlen($password) > 55) {
                
    $errors true;
                
    $passwordError 'The password you have entered is invalid, please make sure its 3 - 55 characters long!';
            } else if (!
    preg_match($regex$email)) {
                
    $errors true;
                
    $emailError 'The email address you entered is invalid!';
            } else if (
    $email != $emailmatch) {
                
    $errors true;
                
    $emailcError 'The confirmation email address you entered does NOT match the first email address!';
            } else if (
    $password != $passwordmatch) {
                
    $errors true;
                
    $passwordcError 'The confirmation password you entered does NOT match the first password!';
            }
            
            if (!
    $errors) {
                
    $result mysqli_query($link"SELECT username FROM members WHERE username = '$username'");
                
    $user_numrows mysqli_num_rows($result);
                
    mysqli_free_result($result);
                
                if (
    $user_numrows 0) {
                    
    $usernameError 'Sorry but the username you have chosen is already in use, please try another username!';
                }
                
                
    $result mysqli_query($link"SELECT email FROM members WHERE email = '$email'");
                
    $email_numrows mysqli_num_rows($result);
                
    mysqli_free_result($result);
                
                if (
    $email_numrows 0) {
                    
    $emailError 'Sorry but the email you have entered is already in use, please try another email address!';
                }
                
                if (!
    mysqli_query($link"INSERT INTO members SET username = '$username', email = '$email', password = '" md5($password 'salt') . "'")) {
                    
    $error 'Error: ' mysqli_error($link);
                    include 
    'error.php';
                } else {
                    include 
    'success.php';
                }
                
                exit;
            }
        }
    }

    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <title>website</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <link href="style1.css" rel="stylesheet" type="text/css" media="screen" />
    </head>
    <body>

    <div id="wrapper">
        <div id="main">
            <div id="register">
                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
                    <?php
                    
    if (isset($errors) && $errors) {
                        echo 
    '<font color="red" style="text-align: center;">One or more fields are invalid, please make sure all fields have a value!</font><br />';
                    }
                    
    ?>
                    Username: <input type="text" name="username" />
                    <?php echo isset($usernameError) ? '<br />' $usernameError ''?><br />
                    Your Email: <input type="text" name="email" />
                    <?php echo isset($emailError) ? '<br />' $emailError ''?><br />
                    Email again: <input type="text" name="emailmatch" />
                    <?php echo isset($emailcError) ? '<br />' $emailcError ''?><br />
                    Password: <input type="password" name="password" />
                    <?php echo isset($passwordError) ? '<br />' $passwordError  ''?><br />
                    Password again: <input type="password" name="passwordmatch" />
                    <?php echo isset($passwordcError) ? '<br />' $passwordcError  ''?>
                    <br /><br />
                    <input type="submit" name="register" value="Go" />
                </form>
            </div> <!-- end of register -->
        </div> <!-- end of main -->
        <?php include $_SERVER['DOCUMENT_ROOT'] . '/includes/footer.php'?>
    </div> <!-- end of wrapper -->

    </body>
    </html>

  10. #10
    SitePoint Zealot
    Join Date
    May 2010
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks very much, it looks much nicer than my code (really curious as to mine doesn't work.. everything but inserting the user works really well!)

    but it is doing the same thing mine used to do - inserting the user even if the username and/or email is already taken...

    the errors all work fine though (except username/email taken)

    hmm

  11. #11
    SitePoint Zealot
    Join Date
    May 2010
    Posts
    100
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Woah I think I actually fixed mine, just took out the 'else' before my final query.. seems to be working..!!!

    now I can just implement your beautiful error handling, much prefer it over mine.. thanks so much for all of your help!

    (as soon as I post this it is going to stop working. )


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •