Real World Usage For If/Else
You could create a simple password protected area using If/Else. A PHP page with a conditional statement could be set up to process an HTML login form. A variable “$password” could be set, and the Header command could be used to redirect on success or failure.
Your HTML page would be a simple form...
<form action="login.php" method="post">
<INPUT type="password" name="password">
<input type="submit">
</form>
This HTML form will set the variable in the “action” page (named login.php in this example) with the $_POST command (more on this later) and do one of two things: If the password is correct, it will show the desired content. If it is NOT correct, it will redirect to another URL (or page). Since the action is in PHP, viewing the source in the web browser isn’t going to reveal the password.
...And your PHP “Action” page would be an If/Else combined with a Redirect...
<?php
if($_POST['password'] == 'some_password'){
echo “
<!---Put your protected HTML content here...-->
“ ;
} else {
header ("location: some_error_page.html");
}
?>
...And Voila! A simple way to password protect a page. I wouldn’t use this for sensitive stuff (like putting your social security number online) but it’s good for a simple, single layer of security.
IF, meet ELSE. ELSE, meet ELSEIF
The IF/ELSE statement is wonderful if you need to check for only one condition. But, what if you need to check for multiple conditions? Like, for instance, IF a truck is a Dodge, do this...ELSE a truck is a Chevy, do this...but what if you need to have options if a truck was a Ford?
In this example, we simply want to see if a truck is a Dodge or not. We can do this with IF / ELSE...
<php
$truck = "Chevy";
if($truck == "Dodge"){
echo "It’s Ram Tough!";
} else {
echo "We’ll Be There!";
}
?>
Now, if we wanted to see if the truck was a Ford, we’d add the ElseIf statement...
<php
$truck = "Chevy";
if($truck == "Dodge"){
echo "It’s Ram Tough!";
} elseif {$truck == “Ford”}
echo “Built Ford Tough!”;
} else {
echo "We’ll Be There!";
}
?>
...And so on. You could continue to use ElseIf to declare other Trucks. One thing to remember about ElseIf is that it can’t be used without IF. So what if you have a lot of ElseIf’s?? Let’s see what’s behind the curtain, Bob...
|