if and else statement

can someone explain to me more in depth

Page 1 of 1

1 Replies - 1015 Views - Last Post: 04 November 2009 - 09:45 AM Rate Topic: -----

#1 chris_s_22  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 74
  • Joined: 27-December 08

if and else statement

Posted 04 November 2009 - 07:01 AM

i was given the majority of this code from someone who told me they new what they was doing.
ive started to disect it and add bits to suit my needs
looking through the whole script ive raised questions about the confusion of the whole if and else statements.
Heres my code im using
<?php
include 'Connect.php'; // The conection file connects to database which also includes the functions page.

if(isset($_POST[submit])) // 1 
{
   	 include 'index.php'; // 2 
   	 exit;
}
else  // 3
{
//CHECKS FORM
	if (empty($_POST['username']) || empty($_POST['email']) || empty($_POST['password']) || empty($_POST['confirmpassword']))// 4
	{	
		$missing_error = 'One or more fields missing';
		include 'index.php';
		exit;
	}
//CHECKS USERNAME
	if(preg_match("/^[a-z\d]{5,12}$/i", $_POST[username])) // 5
	{}
	else
	{  
		// Reshow the form with an error
		$username_error = "Your username must only contain letter and numbers and be at least 5 characters but no longer than 12 characters in length!<br />";
		include 'index.php';
		exit;  
	}
//CHECKS EMAIL
	if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $_POST[email])) // 6
	{  
		$email_error = "The e-mail you entered was not in the proper format!"; 
		include 'index.php';
		exit; 
	}
//CHECKS PASSOWORD		 
	if (preg_match('/^[a-z\d]{6,12}$/i', $_POST[password]))  // 7
	{}
	else
	{ 
		$password_error = "Your password must only contain letter and numbers and be at least 6 characters but no longer than 12 characters in length!<br />";
		include 'index.php';
		exit;  
	}
// CHECKS CONFIRMPASSWORD	
	if ($_POST['password'] != $_POST['confirmpassword'])// 8
	{
		$confirmpassword_error = 'Your passwords do not match';
		include 'index.php';
		exit;
	}
	
	// 9
	user_register ($_POST['username'], $_POST['email'], $_POST['dobday'], $_POST['dobmonth'], $_POST['dobyear'], $_POST['password']);
	echo "registered";
}
?>



1 - this checks if the data was posted from the form submitted right?
anyone know of a secure way check that it came from my form and not someone submitting there own form.

after reading lots of tutorials i came to understand this is basic principle of using if and else statments.
if (condition)
  {code to be executed if condition is true;}
else
 { code to be executed if condition is false;}
 


2 - This seems to tell the script what to do if it fails. shouldnt this be what it returns true? hence the basic principle is wrong?
3 - This seems to tell script what to do if it true. shouldnt this be what it returns false?
4 - shouldnt this statement have if and else statments?
currently if feild is empty it shows the error message
but if someone enters something in the feild it continues to check next statement so does seem to work the way it is
i need to understand why and how it works in this format.
5 - This is in the format i have come to understand and believe to be true
6 - same question as 4
7 - This is again the format i have come to understand and believe to be true
8 - This again doesnt have both else and if statments why?
9 - This what happens if all checks have been successful...
but with it been in the else part of the statement shouldnt this be what happens if there was a error

if the basic principle is correct what would be my process to display all errors once all checks have been made.
currently it does a check, and, if error displays the page with just the first error it encounters
logic tells me that the current way is only gonna frustrate users exspcially if they make a mistake on each input feild

im guessing i just need to remove the following code for each error statement, am i right?
include 'index.php';
		exit;



if you see any mistakes or problems that i will encounter in future by using this script feel free to point them out

im not asking for someone to do the code but more to explain in depth but feel free to show me examples

Is This A Good Question/Topic? 0
  • +

Replies To: if and else statement

#2 jaql  Icon User is offline

  • D.I.C Head

Reputation: 7
  • View blog
  • Posts: 73
  • Joined: 19-October 09

Re: if and else statement

Posted 04 November 2009 - 09:45 AM

I just wrote something based off of what you posted, but it is quite different and will probably look confusing. I'll do my best to not leave you confused :)

Here is the code in its entirety:

Here's a file I created called success.php:
<?php
function clean($string) {
  $string = trim($string);
  $string = stripslashes($string);
  return $string;
}

function user_register($username, $email, $day, $month, $year, $password) {
  $message  = "Username: $username<br/ >";
  $message .= "Password: $password<br/ >";
  $message .= "Email: $email<br/ >";
  $message .= "Date of Birth: $day-$month-$year<br/ >";
  $message .= "You have successfully registered!";

  return $message;
}

$count = NULL;
$error = array(
  'Your username must only contain letter and numbers and be at least 5 characters but no longer than 12 characters in length!',
  'Your password must only contain letter and numbers and be at least 6 characters but no longer than 12 characters in length!',
  'Your passwords do not match',
  'The e-mail you entered was not in the proper format!',
);

if (isset($_POST['submit'])) {
  $username   = preg_match('/^[a-z\d]{5,12}$/i', $_POST['username']) ? clean($_POST['username']) : $count++;
  $password   = preg_match('/^[a-z\d]{6,12}$/i', $_POST['password']) ? clean($_POST['password']) : $count++;
  $confirm_pw = ($_POST['password'] == $_POST['confirmpassword']) ? clean($_POST['confirmpassword']) : $count++;
  $email	  = preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $_POST['email']) ? clean($_POST['email']) : $count++;
  $day		= $_POST['dobday'];
  $month	  = $_POST['dobmonth'];
  $year	   = $_POST['dobyear'];
  
  if ($count) {
	echo "There are errors:<br />";
	for ($i=0; $i <= $count; $i++) {
	  echo $error[$i] . "<br />";
	}
	echo "Please go back and re-submit your form.<br/>";
  }
  else {
	echo user_register($username, $email, $day, $month, $year, $password);
  }
}
else {
  echo "You cannot access this page directly.";
  //header("Location: index.php");
}



Here's a mock registration form called form.php:
<html>
  <head>
	<title>Test</title>
  </head>
  <body>
	<form action="success.php" method="post">
	  <div>
		<label for="Username">Username:</label>
		<input type="text" name="username" id="username"/>
	  </div>
	  <div>
		<label for="Password">Password:</label>
		<input type="password" name="password" id="password"/>
	  </div>
	  <div>
		<label for="Confirm Password">Confirm Password:</label>
		<input type="password" name="confirmpassword" id="confirmpassword"/>
	  </div>
	  <div>
		<label for="Email">Email:</label>
		<input type="text" name="email" id="email"/>
	  </div>
	  <div>
		<label for="Date of Birth">Date of Birth (DD/MM/YYYY):</label>
		<input type="text" name="dobday" id="dobday"/>
		<input type="text" name="dobmonth" id="dobmonth"/>
		<input type="text" name="dobyear" id="dobyear"/>
	  </div>
	  <div>
		<input type="submit" name="submit" id="submit" value="Submit"/>
	  </div>
	</form>
  </body>
</html>



And here's success.php in pieces...

First off I created a small function called clean()
function clean($string) {
  $string = trim($string);
  $string = stripslashes($string);
  return $string;
}


This will take what's passed to it and remove white space from the beginning and end of the string, strip backslashes from the string, and then return a new, "clean" string to work with. It's good practice to do something similar to all form input via a user.

You'll see a I added a function called user_register() just so I had something to return if the form was successfully submitted.
function user_register($username, $email, $day, $month, $year, $password) {
  $message  = "Username: $username<br/ >";
  $message .= "Password: $password<br/ >";
  $message .= "Email: $email<br/ >";
  $message .= "Date of Birth: $day-$month-$year<br/ >";
  $message .= "You have successfully registered!";

  return $message;
}


All it does is return a string called $message that contains the input from the form.

Next you'll see a variable called $count and an array called $error
$count = NULL;
$error = array(
  'Your username must only contain letter and numbers and be at least 5 characters but no longer than 12 characters in length!',
  'Your password must only contain letter and numbers and be at least 6 characters but no longer than 12 characters in length!',
  'Your passwords do not match',
  'The e-mail you entered was not in the proper format!',
);


$count is set to NULL initially because if there are errors, it will begin to keep track of them for us in a very generic way. If there are no errors, it just stays empty (null). Note: you may think setting $count to 0 initially is the same as setting it to NULL, but in this small script, if it's set to 0, an error will always be printed. This probably isn't the most efficient way to do error checking anyway, but it's something to get started with.

$error is an array of your error messages. Notice they don't have keys hard-coded, so to access them you'd just have to do $error[0], $error[1], etc. This is where the problem with $count = 0 comes in. If $count always equals 0, the first value of the array will always be printed and your form will never be successfully submitted. This should probably be changed like I said above, but moving on...

Here's the opening of the main if block...

if (isset($_POST['submit'])) {


This says if the submit button from form.php has been pressed, do something. isset($_POST['submit']) will only return true if the button has been pressed. 'submit' refers to the value name attribute of the input button element on form.php.

This next part may be the most confusing and sorry for writing it this way, but it'll all end up the same any way you do it:
$username   = preg_match('/^[a-z\d]{5,12}$/i', $_POST['username']) ? clean($_POST['username']) : $count++;
  $password   = preg_match('/^[a-z\d]{6,12}$/i', $_POST['password']) ? clean($_POST['password']) : $count++;
  $confirm_pw = ($_POST['password'] == $_POST['confirmpassword']) ? clean($_POST['confirmpassword']) : $count++;
  $email	  = preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $_POST['email']) ? clean($_POST['email']) : $count++;
  $day		= $_POST['dobday'];
  $month	  = $_POST['dobmonth'];
  $year	   = $_POST['dobyear'];


So the confusing parts are: $username, $password, $confirm_pw, and $email. If you look at the values of those variables, you'll see a bunch of ?'s and :'s. These are ternary operators.

What they are really saying is:
$variable_name = condition ? if true : if false;



This is just like writing a normal if/else block:
if (condition) {
  true
} else {
  false
}



Anyway, what these variables are doing is all of your pattern matching. They are saying if the input from the form matches the pattern, set the variable equal to the clean version of the form input. However, if the input does not match the pattern, add 1 to $count. So, if you really don't like the look of ternary operators, you could do something like:
if (preg_match('/^[a-z\d]{5,12}$/i', $_POST['username'])) {
  $username =  clean($_POST['username']);
} else {
  $count++;
}



...and so on for the other statements.

So next part of the script checks to see if $count is true because if it's true, it obviously contains a number, which means there are some errors:
if ($count) {
	echo "There are errors:<br />";
	for ($i=0; $i <= $count; $i++) {
	  echo $error[$i] . "<br />";
	}
	echo "Please go back and re-submit your form.<br/>";
  }
  else {
	echo user_register($username, $email, $day, $month, $year, $password);
  }


So if $count is true, the for loop uses $count as the index and goes through the $error array printing as many errors as $count holds. Note again, this is not the best way of doing this. It works because of the order of logic and the order the array is in. For example, if the variables above this if/else block were sorted this way..
 $email	  = preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/', $_POST['email']) ? clean($_POST['email']) : $count++;
 $password   = preg_match('/^[a-z\d]{6,12}$/i', $_POST['password']) ? clean($_POST['password']) : $count++;
$username   = preg_match('/^[a-z\d]{5,12}$/i', $_POST['username']) ? clean($_POST['username']) : $count++; 
  $confirm_pw = ($_POST['password'] == $_POST['confirmpassword']) ? clean($_POST['confirmpassword']) : $count++; 
  $day		= $_POST['dobday'];
  $month	  = $_POST['dobmonth'];
  $year	   = $_POST['dobyear'];


You'd have to match the $error array to the order of how the variables are declared.

Anyway, if the form fails, you'll receive output similar to this:

Quote

There are errors:
Your username must only contain letter and numbers and be at least 5 characters but no longer than 12 characters in length!
Your password must only contain letter and numbers and be at least 6 characters but no longer than 12 characters in length!
Your passwords do not match
The e-mail you entered was not in the proper format!
Please go back and re-submit your form.


Now if $count is still NULL by the time the script gets to this block, your values will be passed to my version of user_register and you'll receive something like:

Quote

Username: woot123
Password: blah1234
Email: mail@address.com
Date of Birth: 01-12-1920
You have successfully registered!


The last part of the script prints a message to the screen if someone visits success.php without actually submitting a form (and by this I mean actually clicking the submit button):
else {
  echo "You cannot access this page directly.";
  //header("Location: index.php");
}


If you uncomment header("Location: index.php");, and then directly visit success.php without filling out a form, you would be redirected back to index.php right away.

Hopefully I helped a little and sorry if I was confusing. Again, there is much more you can do, probably in a better way as well, but hopefully this is a start.

Good luck.

This post has been edited by jaql: 04 November 2009 - 09:53 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1