Jump to content

Need help with a registration script


p3nguattack

Recommended Posts

Hello everyone. I've been working on this script for a while now, and have had some ups and downs. As of now, I don't get any errors, but there are a few problems that I need to fix and can't figure out how. First, When I'm echoing the data back in the "value" of the form, nothing shows up, ever. The !isset(_POST['submit'] at the top used to be at the bottom of the form processing as an else statement(which should have worked fine, but I remembered when I had a variable $message in it, my $session->message() function wouldn't work. I renamed that variable and it started working just fine(my session class automatically puts a $message variable on my pages for my output_message() to work), so I thought maybe it was for some reason removing those values from my variables(even though that shouldn't have fixed the problem considering the only way the output_message() would spit anything out is if a form was submitted) and that's why they wouldn't echo). I know the variables are being set and passed through, because if I don't get any errors and the username doesn't already exist, it registers just fine, and my database reflects the same things entered.

 

My second problem is that neither  the code for the passwords or the emails matching are working. I had them working before, but I had them set up poorly and decided to rewrite them. Before I had them as

if $_POST['password/email'] == $_POST['password/email confirm'] {$password/email = $_POST['password/email'] } else { $session->message = "failed"; redirect_to('register.php').

Of course they were separate statements, but I think you get the point. That worked for me, but I didn't like having the redirect in there(it wouldn't give all the errors either, that function only displays one anyway until I put them in a list like I have now. It works a lot better.).

 

I'll post the whole page code for you to look at,  and if you'd like to know what any of the functions I use look like just ask and I'll post those too, but their names pretty much say exactly what they do.

 

<!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> COMING SOON!</title>
	<link href="stylesheets/main.css" rel="stylesheet" type="text/css" />
</head>

 

<?php
require_once('includes/initialize.php');
if ($session->is_logged_in()) { $session->message("You are already registered."); redirect_to("index.php"); }




// START FORM PROCESSING

if (!isset($_POST['submit'])) {
 // Form has not been submitted.
$user = new User;
$username = "";
$password = "";
$first_name = "";
$last_name = "";
$email = "";
$join = "";
$auth = "";


} elseif(isset($_POST['submit'])) { // Form has been submitted.
$user = new User;
$first_name = trim($_POST['firstname']);
$last_name = trim($_POST['lastname']);
$passwordc1 = trim($_POST['passwordc']);
$passwordc2 = trim($_POST['passwordc']);
$username = trim($_POST['username']);
$emailc1 = trim($_POST['email']);
$emailc2 = trim($_POST['email']);
//$dob = trim($_POST['dob']);
$errlist = "";

// Check if first name has a value
if(empty($first_name)) {
	$errlist .= "<li>You must enter your first name</li>";
}
// Check if last name has a value
if(empty($last_name)) {
	$errlist .= "<li>You must enter your last name</li>";
}
// Check that both email, and email confirm were submitted, and they match
if(empty($emailc1)) {
	$errlist .= "<li>You must enter an email address</li>";
}
if(empty($emailc2)) {
	$errlist .= "<li>You must confirm your email address</li>";
}
if($emailc1 !== $emailc2) {
	$errlist .= "<li>Your email addresses do not match</li>";
} else {
	$email = $emailc2;
}
// Check if username has a value.
if(empty($username)) {
	$errlist .= "<li>You must enter a username</li>";
}
// Check database to see if username exist.
$found_user = User::check_username($username);
if($found_user) {
$errlist .= "<li>Username already exists</li>";
}


// Check that both password, and password confirm were submitted, and they match
if(empty($passwordc1)) {
	$errlist .= "<li>You must enter an email address</li>";
}
if(empty($passwordc2)) {
	$errlist .= "<li>You must confirm your email address</li>";
}
if($passwordc1 !== $passwordc2) {
	$errlist .= "<li>Your email addresses do not match</li>";
} else {
	$password = $passwordc2;
}
// if errors, redirect (here) and show them.
if(!empty($errlist)) {
	$session->message($errlist);
	redirect_to('register.php');
}


if(!$found_user && empty($errlist)) {
	$user->username = $username;
	$user->password = $password;
	$user->first_name = $first_name;
	$user->last_name = $last_name;
	$user->joined = trim($_POST['join']);
	$user->auth = trim($_POST['auth']);
	$user->email = $email;
	$user->dob = trim($_POST['join']);



	$user->create();
	$userpass = User::authenticate($username, $password);
	$session->login($userpass);

	$session->message("You have successfull registered!");
	redirect_to('account.php');

}
}
?> 

 

<body>
<div id="wrapper">
    <div id="bodyContent">
    <?php require ('layouts/top_nav.php'); ?>
        <ul>
        
	<?php echo output_message($message); echo $first_name; ?>
        </ul>
        <div class="center">
        	<!-- LEADERBOARD AD -->
        	<?php echo $user->leaderboard; ?>
        </div>
        <!-- START BODY CONTENT HERE -->

    <table>
    <form action="register.php" method="post" enctype="multipart/form-data" >    

        <input name="join" type="hidden" value="<?php echo date("Y-m-d H:i:s", time()); ?>" maxlength="20" />
    	<input name="auth" type="hidden" value="1" />
    <tr>
  	<td>First Name:</td><td><input name="firstname" type="text" value="<?php echo $first_name; ?>" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>Last Name:</td><td><input name="lastname" type="text" value="<?php echo $last_name; ?>" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>E-mail:</td><td><input name="email" type="text" value="<?php echo $email; ?>" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>Confirm e-mail:</td><td><input name="emailc" type="text" value="<?php echo $email; ?>" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>Username:</td><td><input name="username" type="text" value="<?php echo $username; ?>" maxlength="20"  /><br /></td>
    </tr>
    <tr>
<td>Password:</td><td><input name="password" type="password" value="<?php echo $password; ?>" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>Confirm password:</td><td><input name="passwordc" type="password" value="<?php echo $password; ?>" maxlength="20" /><br /></td>
    </tr>
    
    <tr>
    <td><input name="submit" type="submit" value="Register" /></td>
    </tr>
</form>
</table>
</div>
</div>
</body>
</html>

 

I was also wondering if anyone could suggest a way for me to do my date of birth field. I wanted to have a dropdown menu for each value, but I'm not sure how to do that, or how that data would be retrieved by php.

 

Also I was wondering if there was any way that I could query the database after the user types in their username and either display a check mark next to it, or an "already taken" message before they submit the form. I was googling it, and found a bunch of stuff about how you could do it with javascript, but nothing on php.

 

Thanks in advance for any help you may give me. I really appreciate it, and would love to have this page working soon. Until then, it's time to go work on my account page :P.

Link to comment
Share on other sites

Firstly, make sure you're coding with error_reporting on and set to E_ALL.

 

I was also wondering if anyone could suggest a way for me to do my date of birth field. I wanted to have a dropdown menu for each value, but I'm not sure how to do that, or how that data would be retrieved by php.

The same way the rest of the form values are handled. You then create a string to hold all three values, and make the MySQL column be DATE type.

 

Also I was wondering if there was any way that I could query the database after the user types in their username and either display a check mark next to it, or an "already taken" message before they submit the form. I was googling it, and found a bunch of stuff about how you could do it with javascript, but nothing on php.

You have to use AJAX, which combines Javascript and a server side script like PHP. Check out jQuery there are some good tutorials on doing this.

 

Link to comment
Share on other sites

Not quite right. :P

echo strtotime ("1950/04/01");
// -623379600

echo date ("d/m/Y", -623379600);
// 01/04/1950

 

If course, if you're going to save it to a database you should use the proper field type for said database system. However, when working with dates in PHP, a Unix timestamp is the easiest way to handle it. Even for those born prior to 1st of January 1970. ;)

Link to comment
Share on other sites

I appreciate the replies, and to first reply, I have my php.ini set up exactly as you described. I did try to use the jquery datepicker, but I'm not familiar with javascript, and I think I had it called wrong or something. Everything I tried had a text box, but no calendar when you clicked it (as the example from the tutorial did). I thought I had my code correct, but something had to be wrong. I'm not as concerned with that at the moment as much as the first two issues I posted though. If I can get them resolved I'll start messing with the datepicker some more.

Link to comment
Share on other sites

To get back to the two issues you described in the OP, the reason your form is not getting the inputted values is quite simple: It's because of the redirect.

You don't want to redirect the user in the case of an error, only when they've successfully logged in. In the case of an error, simply call the function to show the form again.

 

As for the second error, please re-check where you retrieve the password details:

	$passwordc1 = trim($_POST['passwordc']);
$passwordc2 = trim($_POST['passwordc']);

Link to comment
Share on other sites

Alright I have that figured out, I can't believe I missed the $_POST names like that. Just coding a lot must have been tired lol. Thanks Christian! Here's my new improved code.

 

<!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> COMING SOON!</title>
	<link href="stylesheets/main.css" rel="stylesheet" type="text/css" />
</head>
<?php
require_once('includes/initialize.php');
if ($session->is_logged_in()) { $session->message("You are already registered."); redirect_to("index.php"); }




// START FORM PROCESSING

if (!isset($_POST['submit'])) {
 // Form has not been submitted.
$user = new User;
$username = "";
$password = "";
$first_name = "";
$last_name = "";
$email = "";
$join = "";
$auth = "";


} elseif(isset($_POST['submit'])) { // Form has been submitted.
$user = new User;

$first_name = trim($_POST['firstname']);
$last_name = trim($_POST['lastname']);
$passwordc1 = trim($_POST['password']);
$passwordc2 = trim($_POST['passwordc']);
$username = trim($_POST['username']);
$emailc1 = trim($_POST['email']);
$emailc2 = trim($_POST['emailc']);
//$dob = trim($_POST['dob']);
$errlist = "";

// Check if first name has a value
if(empty($first_name)) {
	$errlist .= "<li>You must enter your first name</li>";
}
// Check if last name has a value
if(empty($last_name)) {
	$errlist .= "<li>You must enter your last name</li>";
}
// Check that both email, and email confirm were submitted, and they match
if(empty($emailc1)) {
	$errlist .= "<li>You must enter an email address</li>";
}
if(empty($emailc2)) {
	$errlist .= "<li>You must confirm your email address</li>";
}
if($emailc1 !== $emailc2) {
	$errlist .= "<li>Your email addresses do not match</li>";
} else {
	$email = $emailc2;
}
// Check if username has a value.
if(empty($username)) {
	$errlist .= "<li>You must enter a username</li>";
}
// Check database to see if username exist.
$found_user = User::check_username($username);
if($found_user) {
$errlist .= "<li>Username already exists</li>";
}


// Check that both password, and password confirm were submitted, and they match
if(empty($passwordc1)) {
	$errlist .= "<li>You must enter a password</li>";
}
if(empty($passwordc2)) {
	$errlist .= "<li>You must confirm your password</li>";
}
if($passwordc1 !== $passwordc2) {
	$errlist .= "<li>Your passwords do not match</li>";
} else {
	$password = $passwordc2;
}
// if errors, redirect (here) and show them.
if(!empty($errlist)) {
	$errcount =  substr_count($errlist, "/");

}


if(!$found_user && empty($errlist)) {
	$user->username = $username;
	$user->password = $password;
	$user->first_name = $first_name;
	$user->last_name = $last_name;
	$user->joined = trim($_POST['join']);
	$user->auth = trim($_POST['auth']);
	$user->email = $email;
	$user->dob = trim($_POST['join']);



	$user->create();
	$userpass = User::authenticate($username, $password);
	$session->login($userpass);

	$session->message("You have successfull registered!");
	redirect_to('account.php');

}
}
?> 
<body>
<div id="wrapper">
    <div id="bodyContent">
    <?php require ('layouts/top_nav.php'); ?>
        <ul>
        
	<?php echo output_message($message);?>
        </ul>
        <div class="center">
        	<!-- LEADERBOARD AD -->
        	<?php echo $user->leaderboard; ?>
        </div>
        <!-- START BODY CONTENT HERE -->
<?php if(!isset($_POST['submit']) || !empty($errlist)) {
if(isset($errlist)) { 
	echo "There were ".$errcount." errors with your information.";
	echo $errlist;
 }
echo '
    <table>
    <form action="register.php" method="post" enctype="multipart/form-data" >    

        <input name="join" type="hidden" value="'. date("Y-m-d H:i:s", time()) .'" maxlength="20" />
    	<input name="auth" type="hidden" value="1" />
    <tr>
  	<td>First Name:</td><td><input name="firstname" type="text" value="'. @$first_name .'" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>Last Name:</td><td><input name="lastname" type="text" value="'. @$last_name.'" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>E-mail:</td><td><input name="email" type="text" value="'.@$email.'" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>Confirm e-mail:</td><td><input name="emailc" type="text" value="'.@$email.'" maxlength="50" /><br /></td>
    </tr>
    <tr>
    <td>Username:</td><td><input name="username" type="text" value="'.@$username.'" maxlength="20"  /><br /></td>
    </tr>
    <tr>
<td>Password:</td><td><input name="password" type="password" value="'.@$password.'" maxlength="20" /><br /></td>
    </tr>
    <tr>
    <td>Confirm password:</td><td><input name="passwordc" type="password" value="'.@$password.'" maxlength="20" /><br /></td>
    </tr>
    
    <tr>
    <td><input name="submit" type="submit" value="Register" /></td>
    </tr>
</form>
</table>

'; } ?>



    


    
    	<!-- END BODY CONTENT HERE -->
  
    
    	
</div>
</div>
</body>
</html>

 

Apparently I had to do away with using my output_message function if I wanted to be able to echo the form processing errors along with the values the users put in. It works by storing the message in the $_SESSION then moving it to the session class I'm assuming after a redirect, or a new page(it works from page to page. Any page to any other page on the site for whatever reason, that's what it was made for).  So I did a substr_count for that part of the form processing instead, then echo'd that count, followed by the $errlist. Works much better this way. Thanks everyone. Now if only I could get that jquery down lol. Anyone know a link for a tutorial for complete newbies to javascript?

Link to comment
Share on other sites

I'm glad I could help, and that you got it sorted out.

 

That said, you're handling the error conditions in a way that's a lot more complicated than it should be. I recommend that you look into using functions, or even a templating system, to make things a lot easier for you. The ability to control the exit points on parts of the code is invaluable, and will make your scripts a whole lot more flexible than what you're seeing above.

Trust me, you'll want to change the modus operandi you've been using so far.

Link to comment
Share on other sites

To give you an example of how I'd do this, in a quick and not quite complete manner:

<?php

// If user is already logged in, then he/she must be registered. 
if ($_SESSION['logged_in']) {
$template->message = $template->already_registered;
$template->set_page ('index');
return;
}

// Set the default page to show the register form.
$template->set_page ('register_form');

// if form hasn't been posted, exit out of this file to main controller file.
if (!isset ($_POST['submit'])) {
return;
}

// Initialize variables used for validation.
$errors = array ();
$check = true;

// Validate the user-submitted data, saving the results of any failed validation into $check and $errors.
$username = validate ('username', $_POST['username'], $check, $errors);
$email = validate ('email', $_POST['email'], $check, $errors);
$password = validate ('password', $_POST['password'], $check, $errors);

// If passwords doesn't match, mark validation as failed and add to error messages. 
if ($password != '' && $password != $_POST['confirm_pass']) {
$errors[] = $template->passwords_confirmation_not_matching;
$check = false;
}

// If validation failed at any point, show the error messaes and return to main controller file.
if (!$check) {
$errors = "<ul class=\"error\">\n\t<li>".implode ("</li>\n\t<li>", $errors)."</li>\n</ul>\n";
$template->form_errors = sprintf ($template->following_errors_occured, $errors);
return;
}

// Same if the user already exists.
if ($user->exists ($username)) {
$template->form_errors = $template->user_already_exists;
return;
}

// Register a new user, and send him to the confirmation page if succeeds. 
if ($user->new ($username, $email, $password)) {
redirect ('welcome');
}

// In case of errors, show the form again with the correct error message.
$template->form_errors = $template->could_not_save_data; 

 

As you notice I use a template engine to control what gets sent to the browser, and rely upon a "controller" file to include the page-specific code. That way I can use "return" to exit out of the included file, and leave the calling file to deal with constructing the actual output.

Simple, flexible and above all quick to work with. ;)

Link to comment
Share on other sites

That does look a lot easier, I've honestly haven't looked at any templates. I suppose I was doing it this way partially, because I'm still inexperienced and wanted to learn as much as possible from making the site. I'll have to check that out though. I don't quite understand how the return to controller function works  though. I guess that has something to do with never hearing of a controller lol. I've only been working with php for about a month :/. I have to say though, I feel like I'm doing alright so far lol. I have almost a complete website all hardcoded. Of course I do have quite a few classes to make that process a lot easier. Would I be able to find something like that from pear or pecl, or are there specific sites for templates?

Link to comment
Share on other sites

The controller file can look like this, for a very bare-bones example:

<?php
// First retrieve and validate the page requested.
if (isset ($_GET['page'])) {
    $page = preg_replace ('/[^a-z]/', '', $_GET['page']);
} else {
    $page = 'index';
}

// Create the template object.
$output = new Template ();

// Then make sure it exists as an includeable file.
if (!is_file ("php/{$page}.php") {
    // Cast a 404 error.
    die ();
}

// Include it and execute the page-specific code.
include ("php/{$page}.php");

// Read the main content file.
$output->read_file ($page);

// Parse the template files, and print out the result to the browser.
echo $output->parse ();
?>

 

When you call return from an included file, it will stop parsing that file and return back to the file where it was included. This works since include () is a regular function, just like any other function. So the PHP script will continue to parse the main script, as if it had run through all of the code in the included file (which it has, in a way).

The only difference between include () and any other function, is that you're still working within the same variable scope. While normal functions have their own scope, and thus need to have variables passed to them in and returned out.

 

There are a lot of template engines out there, from very basic ones to the really complex ones. Smarty is one of the most popular, but also one of the most complex ones out there. I recommend using a very basic one, at least in the start.

Link to comment
Share on other sites

I was going to say, the tutorial I learned php from recommended smarty but you beat me to it lol. I have one more question and then I suppose I'll mark this thread resolved. If I were to get a templating engine, say smarty for example. Would I have to rewrite all of my pages? I looked into it quite a bit and it really does seem easier than hardcoding it all, but at this stage in my project, I'm not sure I'd want to commit to that if I did have to rebuild everything (and according to what I read, it looks like I do).

Link to comment
Share on other sites

Yes, you would have to rewrite everything. However, learning to use a template engine is a valuable skill, from personal experience I will say it is necessary if you are trying to make a career out of PHP programming.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.