Jump to content
Larry Ullman's Book Forums

Altering Echo Formatting According To Chapter 16


Recommended Posts

Hello! Another post about the site I'm developing. Essentially I have adapted the login.php script and register.php (which I call signup.php) to use on my website.

 

The messages that come up if you forget to type in your email, password; enter an invalid password; or enter passwords that don't match, appear the same as they would in the book if you were to attempt to sign up. See what happens here: forensicoutreach.com/signup.php.

 

But as you can see, it does not fit in the with the look of the site and they kind of float right underneath the nav bar. How could I change this so that the messages fit in neatly with the look of the site? Perhaps so I can have them appear right next to the fields that are incomplete or invalid? You can look at my HTML/CSS of course by viewing the source.

 

The code I used for the signup page appears below. Many thanks for your help! Amazing forum and moderators.

 

<?php // signup.php

// Include the configuration file and the HTML header.

require_once('includes/config.inc.php');

$page_title = 'Sign up';

include('includes/header.html');

// Create the conditional that checks for form submission + database connection script.

if (isset($_POST['submitted'])) {
require_once('includes/mysqli_connect.php');

// Trim the incoming data and set some flag variables.

$trimmed = array_map('trim', $_POST);
$fn = $ln = $e = $p = FALSE;

$fn = FALSE;
$ln = FALSE;
$e = FALSE;
$p = FALSE;

// Validate the first and last names.

if (preg_match ('/^[A-Z \'.-]{2,20}$/i', $trimmed['first_name'])) {
$fn = mysqli_real_escape_string($dbc, $trimmed['first_name']);
} else {
echo '<p>Please enter your first name.</p>';
}

if (preg_match ('/^[A-Z \'.-]{2,40}$/i', $trimmed['last_name'])) {
$ln = mysqli_real_escape_string($dbc, $trimmed['last_name']);
} else {
echo '<p>Please enter your last name.</p>';
}

// Validate the email address.

if (preg_match ('/^[\w.-]+@[\w.-]+\.[A-Za-z]{2,6}$/', $trimmed['email'])) {
$e = mysqli_real_escape_string($dbc, $trimmed['email']);
} else {
echo '<p>Please enter your email address.</p>';
}

// Validate the passwords.

if (preg_match ('/^\w{4,20}$/', $trimmed['password1']) ) {
if ($trimmed['password1'] == $trimmed['password2']) {
	$p = mysqli_real_escape_string ($dbc, $trimmed['password1']);
} else {

echo '<p>Your passwords did not match.</p>';

}

} else {
echo '<p>You have entered an invalid password.</p>';
}

// Is this a unique email address?

if ($fn && $ln && $e && $p) {
$q = "SELECT user_id FROM users WHERE email='$e'";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br/>MYSQL Error: " . mysqli_error($dbc));

// If the email address is unused, register the user:

if (mysqli_num_rows($r) == 0) {

					$a = md5(uniqid(rand(), true));
					$q = "INSERT INTO users (email, pass, first_name, last_name, active, registration_date) VALUES ('$e', SHA1('$p'), '$fn', '$ln', '$a', NOW() )";
					$r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error:" . mysqli_error($dbc));

					// Send an email if the query worked.

					if (mysqli_affected_rows($dbc) == 1) {
						$body = "
						Welcome to Forensic Outreach. To activate your account, please click here:\n\n";
						$body .= BASE_URL . 'activate.php?x=' . urlencode($e) . "&y=$a";
						mail($trimmed['email'], 'Welcome to Forensic Outreach', $body, 'From: admin@forensicoutreach.com');
						ob_end_clean();
						$url = BASE_URL . 'success.php';
						header("Location: $url");							
						include ('includes/footer.html');
						exit();

						// Print errors if the query failed.

					} else {
						echo '<p>You could not be registered.</p>';
					}

					} else {
						echo '<p>Email has already been registered.</p>';

					}
} else {

echo '<p>Please reenter your passwords and try again.</p>';
}

mysqli_close($dbc);

} // End of the main submit conditional.

?>

<title>Sign Up</title>

  <div class="content">

     <div class="leftc">


       <h1>Sign Up</h1>
       <h2>Start downloading worksheets, lesson plans and more.</h2>
       <p>Already signed up? <a href="login.php"><strong>Login</strong></a> now.

       <div class="leftcolc">

       </div>


       <div class="leftcolc">
           <h2>It's easy and free.</h2>

           <!-- Script for a login form --> 
           <form action="signup.php" method="post" ><fieldset>
           <p class="form">first name</p> <input type="text" name="first_name" size="20" maxlength="20" value="<?php if (isset($trimmed['first_name'])) echo $trimmed['first_name'];?>"/></p>
           <p class="form">last name</p> <input type="text" name="last_name" size="20" maxlength="40" value="<?php if (isset($trimmed['last_name'])) echo $trimmed['last_name'];?>"/></p>
           <p class="form">email</p> <input type="text" name="email" size="20" maxlength="80" value="<?php if (isset($trimmed['email'])) echo $trimmed['email'];?>"/></p>
           <p class="form">password</p> <input type="password" name="password1" size="20" maxlength="20"/></p>
           <p class="form">confirm password</p> <input type="password" name="password2" size="20" maxlength="20"/></p>

           <p><input type="submit" name="submit" value="Sign Up" />
           <input type="hidden" name="submitted" value="TRUE" />
           </fieldset>
           </form>
       </div>

       <div class="leftcolc">


       </div>



       <!--/content -->

  </div>

	<!--footer -->


<?php

include('includes/footer.html');

?>


Link to comment
Share on other sites

Hi Shivani,

 

Basically you need to assign them into a styled div or class as currently it looks like there in your wrapper tag, that doesn't seem to have a closing tag btw. Then style the div however you wish in your CSS.

 

As i can see you run a series of if statements and report back on the success of these.

 

What you could do instead is rather than post these errors after each if. Assign the error to a variable and then use a for loop to iterate over the $error array and enclose this for loop inside a div or class.

 

To do this you would:

// initiliase the error array
$error = array();

// run your if statments
if (preg_match ('/^[A-Z \'.-]{2,20}$/i', $trimmed['first_name'])) {
       $fn = mysqli_real_escape_string($dbc, $trimmed['first_name']);
} else {
       $error[] = '<p>Please enter your first name.</p>';
}

// run more if statements

 

and then check to see if the $errors array was empty.

 

if it isnt, echo out a div and iterate your for loop in here stating the errors.

echo '<div id="error">'; // Open CSS tag
// complete for loop in here
echo '</div>'; // close css tag

 

This way you could style the div, in color, text font and position it where you want on the page.

  • Upvote 1
Link to comment
Share on other sites

Hi Shivani,

 

Basically you need to assign them into a styled div or class as currently it looks like there in your wrapper tag, that doesn't seem to have a closing tag btw. Then style the div however you wish in your CSS.

 

As i can see you run a series of if statements and report back on the success of these.

 

What you could do instead is rather than post these errors after each if. Assign the error to a variable and then use a for loop to iterate over the $error array and enclose this for loop inside a div or class.

 

To do this you would:

// initiliase the error array
$error = array();

// run your if statments
if (preg_match ('/^[A-Z \'.-]{2,20}$/i', $trimmed['first_name'])) {
       $fn = mysqli_real_escape_string($dbc, $trimmed['first_name']);
} else {
       $error[] = '<p>Please enter your first name.</p>';
}

// run more if statements

 

and then check to see if the $errors array was empty.

 

if it isnt, echo out a div and iterate your for loop in here stating the errors.

echo '<div id="error">'; // Open CSS tag
// complete for loop in here
echo '</div>'; // close css tag

 

This way you could style the div, in color, text font and position it where you want on the page.

 

Hello again! I've tried to implement your suggestions and basically created this statement to print the $errors array.

 

<?php

       if (empty($error)) {
		echo '' ;
	} else {
		for ($error = 1; $error < count($error); $error++) {
		print $error;

		}

	}


	?> 

 

Needless to say, it's not working. I tried writing just the if statement first to check if the array was empty, and that bit worked when I just asked it to print "Empty" or "Not Empty." Then my approach was to add the for look you suggested to print the array, and that's where I'm really stuck, because it's not printing them. Do you have any more suggestions? Any help would be appreciated!

Link to comment
Share on other sites

<?php

       if (empty($error)) {
                       echo '' ;
               } else {
                       for ($error = 1; $error < count($error); $error++) {
                       print $error;

                       }

               }


?> 

 

You're overwriting the names of variables. You can't have an array called $error and then create your counting variable also called $error, because when you go to print the error from the array it will be referring to the counter variable. I'd also probably use a foreach loop rather than a for loop:

 

// Initialise errors array
$errors = array();

// Conduct validation
if (preg_match ('/^[A-Z \'.-]{2,20}$/i', $trimmed['first_name'])) {
       $fn = mysqli_real_escape_string($dbc, $trimmed['first_name']);
} else {
       $error[] = '<p>Please enter your first name.</p>';
}

// Other validation code goes here

if (empty($errors)){

      // Insert user into database

} else {

       foreach($errors as $error) {

               echo '<p class="error">' . $error . '</p>';

       }

}

 

Finally I'd also recommend looking into using JavaScript/JQuery validation for your site to improve the user experience. You're site looks really good and I find server side validation can be clunky in terms of UX and does decrease conversion rates. That said using a jQuery plugin is not a substitute for server side validation. For security purposes all data should be validated server side as client side controls are easily bypassed. Aside from UX improvements it will also reduce the amount of processing done by your server.

  • Upvote 1
Link to comment
Share on other sites

Hi Stuart,

 

Thanks again for all of your help. I'm pretty good with XHTML/CSS but I'm slowly learning how to make sites dynamic -- and thereby deal with JavaScript and PHP. I will look into using JavaScript as well for validation as it seems to make sense to do so.

 

Thanks for the compliment as well! :)

Link to comment
Share on other sites

Hi again! I took your advice and downloaded a generic JavaScript validator from a website as I'm not familar enough with it to do all the coding myself. The Java works in terms of validation and I thought it could be integrated with the PHP, which would handle the submit function and pass the info along to the database. But that's not happening. Any idea why? New code below and you can see what the page is doing if you visit forensicoutreach.com'signup.php.

 

Any help is appreciated...

 

<?php // signup.php

// Include the configuration file and the HTML header.

require_once('includes/config.inc.php');

$page_title = 'Sign up';

include('includes/header.html');

// Create the conditional that checks for form submission + database connection script.

if (isset($_POST['submitted'])) {
require_once('includes/mysqli_connect.php');

// Trim the incoming data and set some flag variables.

$trimmed = array_map('trim', $_POST);
$fn = $ln = $e = $p = FALSE;

$fn = FALSE;
$ln = FALSE;
$e = FALSE;
$p = FALSE;


// Is this a unique email address?

if ($fn && $ln && $e && $p) {
$q = "SELECT user_id FROM users WHERE email='$e'";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br/>MYSQL Error: " . mysqli_error($dbc));

// If the email address is unused, register the user:

if (mysqli_num_rows($r) == 0) {

					$a = md5(uniqid(rand(), true));
					$q = "INSERT INTO users (email, pass, first_name, last_name, active, registration_date) VALUES ('$e', SHA1('$p'), '$fn', '$ln', '$a', NOW() )";
					$r = mysqli_query($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error:" . mysqli_error($dbc));

					// Send an email if the query worked.

					if (mysqli_affected_rows($dbc) == 1) {
						$body = "
						Welcome to Forensic Outreach. To activate your account, please click here:\n\n";
						$body .= BASE_URL . 'activate.php?x=' . urlencode($e) . "&y=$a";
						mail($trimmed['email'], 'Welcome to Forensic Outreach', $body, 'From: admin@forensicoutreach.com');
						ob_end_clean();
						$url = BASE_URL . 'success.php';
						header("Location: $url");							
						include ('includes/footer.html');
						exit();

						// Print errors if the query failed.

					} else {
						$error[] = '<p>You could not be registered. Please try again<p>';
					}

					} else {
						$error[] = '<p>This email address has already been registered.<p>';

					}
} else {

$error[] = '<p>Please reenter your passwords and try again.<p>';
}

mysqli_close($dbc);

} // End of the main submit conditional.

?>

<title>Sign Up</title>

  <div class="content">

     <div class="leftc">


       <h1>Sign Up</h1>
       <h2>Start downloading worksheets, lesson plans and more.</h2>
       <p>Already signed up? <a href="login.php"><strong>Login</strong></a> now.

       <div class="leftcolc">

       </div>


       <div class="leftcolc">
           <h2>It's easy and free.</h2>

           <!-- Script for a login form --> 

           <form action="signup.php" method="post" form id ="signup"><fieldset>
           <p class="form"><label for='first_name'>first name</label></p> <input type="text" name="first_name" size="20" maxlength="20" value="<?php if (isset($trimmed['first_name'])) echo $trimmed['first_name'];?>"/></p>

           <p class="form"><label for='last_name'>last name</label></p> <input type="text" name="last_name" size="20" maxlength="40" value="<?php if (isset($trimmed['last_name'])) echo $trimmed['last_name'];?>"/></p>

           <p class="form"><label for='email'>email</label></p> <input type="text" name="email" size="20" maxlength="80" value="<?php if (isset($trimmed['email'])) echo $trimmed['email'];?>"/></p>

           <p class="form"><label for="password1">password</label></p> <input type="password" name="password1" size="20" maxlength="20"/></p>

           <p class="form"><label for="password2">confirm password</label></p> <input type="password" name="password2" size="20" maxlength="20"/></p>

           <p><input type="submit" name="submit" value="Sign Up" />
           <input type="hidden" name="submitted" value="TRUE" />
           </fieldset>
           </form>

<script  type="text/javascript">

var frmvalidator = new Validator("signup");
frmvalidator.addValidation("first_name","req","Please enter your first name.");
frmvalidator.addValidation("first_name","maxlen=20", "Enter a name less than 20 characters");
frmvalidator.addValidation("first_name","alpha", "Only alphabetic characters are allowed.");

frmvalidator.addValidation("last_name","req", "Please enter your last name.");
frmvalidator.addValidation("last_name","maxlen=40", "Enter a surname less than 40 characters.");
frmvalidator.addValidation("last_name","alpha", "Only alphabetic characters are allowed.");

frmvalidator.addValidation("email","maxlen=50", "The required email length is less than 50 characters.");
frmvalidator.addValidation("email","req", "Please enter your email address.");
frmvalidator.addValidation("email","email", "Please enter a valid email address.");

frmvalidator.addValidation("password1","maxlen=20", "The required password length is less than 20 characters.");
frmvalidator.addValidation("password1","req", "Please enter a password.");
frmvalidator.addValidation("password1","alphanumeric", "Passwords can only contain numbers and letters.");


frmvalidator.addValidation("password1", "eqelmnt=password2", "The confirmed password does not match the password.");

frmvalidator.EnableOnPageErrorDisplaySingleBox();
frmvalidator.EnableMsgsTogether();

</script>

       </div>

       <div class="leftcolc">
       <p>  
       <div id='signup_errorloc'></div>

       </div>



       <!--/content -->

  </div>

	<!--footer -->


<?php

include('includes/footer.html');

?>

</div>

Link to comment
Share on other sites

Hi Shivani,

 

Like I said in the previous post you can't substitute JavaScript for the PHP coding as you open yourself up to arbitrary input which poses the risk of security issues. When adding the JS validation to the page the underlying PHP logic should remove completely untouched. Think of it as a layer of gloss on top of your web page.

 

It looks like you've removed the PHP validation from your script meaning that if I turn off JS in my browser I can submit any details I want. Specifically the reason your PHP doesn't work is because you have declared all variables to FALSE on this line:

 

$fn = $ln = $e = $p = FALSE;

$fn = FALSE;
$ln = FALSE;
$e = FALSE;
$p = FALSE;

 

Not sure why you've made the same declarations twice? But then you check these to ensure they are TRUE (which they won't be) on this line:

 

if ($fn && $ln && $e && $p) {

 

Just to re-iterate the key point - any client side validation should be in addition to server side validation NOT a substitute for it. Adding JS validation is there to improve the user experience and increase conversion rates - not to eliminate server side validation. Your underlying PHP logic should remain completely unchanged from the non-JS version. Hope that makes everything clear?

 

Just incase my comment in my previous post about reducing processing has confused you - I'll explain. If a normal user submits the page but it has an ill-formed email address the PHP form processes that form, finds errors and presents the same page back to the user - but with a JS version the page will only be submitted and processed once - hence placing less demand on your server.

  • Upvote 1
Link to comment
Share on other sites

JavaScript is a great way to do as Stuart said make your website intervative and alluring. But it doesn't give you any protection if you use it soley to 'validate' your forms. I'd suggest you get your PHP signup process all sorted and working securely, get your colleagues to test it, incase they're experiences throw up any problems. Once your happy with it, then look into how to spice your site up visually or interactively.

 

;)

  • Upvote 1
Link to comment
Share on other sites

  • 4 weeks later...
 Share

×
×
  • Create New...