Goals
Write a set of PHP pages that get input from the user, and generate output based on it. Introduce form interaction, data types, and decision making. Start thinking about application structure.
Notes
Read about HTML forms.
Read Mastering PHP 4, chapter 1, from "Who Are You?" to "Forms and Query Strings."
Read PHP for beginners, pages 3-8.
Read PHP Essentials, Intro to variables, Understanding variable types, PHP operators, and PHP control flow (if statements only).
Stringy things
There are some things you should know about comparing data in PHP. First, note that "Thing" and "thing" are not the same, er, thing. Try this in a PHP page:
if ( 'thing' == 'Thing' ) {
print 'They are the same.';
}
else {
print 'They are not the same.';
}
Suppose you wanted to check data from a form. Suppose you did this on an HTML page:
<input type="text" name="formFieldName">
<button type="submit">Save</button>
Here's some PHP:
$userData = $_POST['formFieldName'];
if ( $userData == 'thing' ) {
print 'You typed thing.';
}
else {
print 'You did not type thing.';
}
If users type "Thing", they'll get the message that they did not type thing.
Hmm. Suppose we wanted users to see the "You typed thing" message even if they typed Thing. Here's one possibility:
$userData = $_POST['formFieldName'];
if ( $userData == 'thing' || $userData == 'Thing' ) {
print 'You typed thing.';
}
else {
print 'You did not type thing.';
}
Try it out. Put it in a PHP page and see what happens. Go on, live a little.
It works! Hooray!
Now try typing THING.
Doh!
The best thing (Thing?) to do is to convert what the user typed to lower (or upper) case before making the comparison. Try this:
$userData = $_POST['formFieldName'];
if ( strtolower($userData) == 'thing' ) {
print 'You typed thing.';
}
else {
print 'You did not type thing.';
}
Now, no matter what the user types - thing, Thing, THING, ThinG - it will work. Look up the strtolower() function on the Web.
Spaced out
Another stringy problem is that 'thing' and ' thing ' (extra spaces) are not the same. Try typing ' thing ' in the input field and see what happens.
Double doh!
There's an easy solution for this, too:
$userData = $_POST['formFieldName'];
$userData = trim(strtolower($userData));
if ( $userData == 'thing' ) {
print 'You typed thing.';
}
else {
print 'You did not type thing.';
}
The trim function kills leading and trailing spaces (and a few other characters).
BTW, notice that I did the conversion in a separate line. No reason. Just to be different.
When there ain't nuthin', dawg
OK, what if the user leaves a form field empty? And that's not allowed? How do you detect that? Why does this paragraph have all these questions? Why don't I just get on with it? Huh? HUH?
We've all seen Web forms where some fields are marked 'required.' What if a user just types in a space? The field isn't empty, technically, but there's no information there. So let's see how to handle that one as well.
Try this:
$userData = $_POST['formFieldName'];
$userData = trim($userData);
if ( $userData == '' ) {
print '<p>Sorry, all form fields must be completed.<p>';
exit();
}
//Process the data
...
Now users who leave the field empty, or just type in spaces, will get an error message.
Getting numbers
Sometimes you want users to enter numbers in input fields, like this:
<label>
How many arms do you have?
<input type='text' size='3' name='armCount'>
*Required
</label>
What can users do wrong? They could:
- Leave the field empty.
- Type text into the field.
- Type in a number less than 0 or more than 2.
- Type in a fractional number of arms, like 1.6.
Notice we're assuming that the users are humans, or at least humanoids, and have 0, 1, or 2 arms. Martians would not be able to use this form. Because they are all dead.
Here's some code. Arranged a bit differently. Just because.
$errorMessage = '';
$armCount = trim($_POST['armCount']);
if ( $armCount == '' ) {
$errorMessage = 'Sorry, you must enter the number of arms you have.';
}
elseif ( ! is_numeric($armCount) ) {
$errorMessage = 'Sorry, you must enter a number.';
}
elseif ( $armCount < 0 || $armCount > 2 || ! is_int($armCount) ) {
$errorMessage = 'Sorry, you must enter a valid number or arms.';
}
if ( $errorMessage != '' ) {
print "<p class='importandNotice'>$errorMessage<p>";
exit();
}
//Process the data
...
First, the code puts an empty string into the variable $errorMessage. Then it runs a bunch o' tests. If any one of them fails, it puts the appropriate message into $errorMessage. When all the tests have been run, if $errorMessage is still empty, the data is OK. If $errorMessage is not empty, something has gone wrong. The message is shown to the user (with the CSS class importantNotice), and the page stops.
I could have done something like this:
elseif ( ! is_numeric($armCount) ) {
print "<p class='importandNotice'>Sorry, you must enter a number.<p>";
exit();
}
This would not be as good, since the code <p class='importandNotice'> would appear lots of times. "So what?", you say. Because if code is repeated, it takes more effort to change it. In this case, I misspelled "important." Did you notice? In the $errorMessage version (the right way), the misspelling only appears once, in the line:
print "<p class='importandNotice'>$errorMessage<p>";
I only need to make one change to fix the problem. However, if I used a line like this for every possible error:
print "<p class='importandNotice'>Sorry, you must enter a number.<p>";
I have to hunt down each 'importandNotice' and change it. It would be easy to miss one.
Have a look at this line:
if ( $armCount < 0 || $armCount > 2 || ! is_int($armCount) ) {
The first two parts are simple enough. Less than 0 arms or more than 2. What's the is_int() for? Some jokers will say they have 1.6 arms. is_int() returns false if the parameter isn't an integer.
Exercises
Exercise 1. Name
Write a program that will input the user's first and last name. If your name is input, the browser will show Welcome Master! (Try entering Kieran Mathieson). Otherwise, it says Welcome (first) (last).
Try it. Solution (try it yourself first).
Exercise 2. Average of three
Write a program to find the average of three numbers entered by the user. You can assume the user makes no typing errors.
Try it. Solution (try it yourself first).
Exercise 3. Age check
Write a program that inputs the user's age, and checks to see whether it is more than 15.
Try it. Solution (try it yourself first).
Exercise 4. Temperature conversion
Write a program that will convert temperatures between celcius and fahrenheit, and vice versa. The formulae are here.
Try it. Solution (try it yourself first).
Exercise 5. Range
Write an HTML page with this in it:
<form method='post' action='out.php'>
<input type='text' name='num1'>
<input type='text' name='num2'>
<input type='submit'>
</form>
Write out.php so that it shows the range between the two numbers. For example, the range between 10 and 2 is 8.
Try it. Solution (try it yourself first).
Exercise 6. Pets
Write a set of pages that act like this. Look at the URLs, and notice how the pages pass data to each other.
Try it. Solution (try it yourself first).