Variables save us some typing, but their real power is that they allow us to do things with information before we know what that information is. This allows us to create websites that customize themselves based on input gathered from a user, usually from a form.
Let's rewrite the online greeting card from last lesson. We'll make it a more generic greeting card site, where any user can make a card for a friend. We'll need to get the user's name, and their friend's name, and then put those names into the greeting.
First we need to write the form. Create a file called
greetings_to_anyone.html in your document root, and start your server. Type this into your new document.
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <title>Create a greeting!</title> </head> <body> <div class="container"> <h1>Fill in your name and your friend's name to create your custom greeting!</h1> <form action="letter.php"> <div class="form-group"> <label for="sender">Your name</label> <input id="sender" name="sender" class="form-control" type="text"> </div> <div class="form-group"> <label for="recipient">Your friend's name</label> <input id="recipient" name="recipient" class="form-control" type="text"> </div> <button type="submit" class="btn">Go!</button> </form> </div> </body> </html>
Here, we're using Bootstrap to style the page; instead of downloading it, I'm just linking to a file that's hosted online.
Let's take a closer look at the different elements in this form.
<form> tag defines the start and end of the form. It takes an attribute that tells it where to submit the information stored in the form. This attribute is called the
action and it should be set to another file somewhere on the server, relative to your document root folder (just like we link to our css files). We will set it to our
letter.php file from last lesson.
Inside of the
<form> tags, we need one
<label> and one
<input> tag for each piece of information we want the user to fill in. The
<input> tag is what creates the field for the user to type into. It must have 3 attributes set:
nameattribute is what we will use in our PHP code to get the value of each input field, so it should be set to something that accurately describes the input you are getting. We want the user to enter their name so that we can use it to sign the letter, so we have named that input field
idcan be anything, so long as it doesn’t match another
idon your page - it's just a way of uniquely identifying the element. Generally, you should use the same value for
<input>tag has many different possible values for the
typeattribute: they are used for everything from checkboxes to menus, dates, colors and numbers. We’re going to set it to
"text"since we just want a person’s name.
<label> tag provides the text to display next to the input field. The
<label> tag takes one attribute called
for, which should match the
id attribute of the corresponding
<input> tag. For example, the
<input> tag with the attribute
id="recipient" should have a
<label> tag with the attribute
<button> tag creates the button that submits the form. It needs to have some text printed on it, like ‘Go!’, and that text is set by just typing it between the opening/closing tags (same as with the
<label> tags). It just has one attribute, also called
type, and it should be set to
Now let’s go over the Bootstrap classes being used in the form. These classes add CSS styles to each element of your form. There are three of them:
"form-group"is used on
<div>s, wrapping together each pair of
"form-control"is used on the
<input>tags. Among other things, it makes the length of the input fields adjust to your screen size.
"btn"is used on the
<button>tag. You can also create colored buttons by using these other Bootstrap button classes:
btn-danger. There are more here on the Bootstrap website.
Now let's modify the file
letter.php from the last lesson. We're going to change the first line of PHP code where we set the variable
$friend_name from this:
$friend_name = "Jennifer";
$friend_name = $_GET["recipient"];
$_GET["recipient"] will give us the value of the
<input> field with the
name attribute set to
"recipient". Similarly, we can get the value of the other input field with the
name attribute set to
"sender" like this:
$my_name = $_GET["sender"];
$_GET part is a special kind of variable called a superglobal, but don’t worry about the fancy term. What is important is that we can get information from our form out of this variable. Just put the name of the input field into the quotes inside the square brackets
Let's try submitting the form ourselves. On the next page, you should be able to see our filled-in form letter. Notice that you can see the information from the form in the browser's URL after hitting "Go!". Mine says:
http://localhost:8000/letter.php?sender=Diane&recipient=Cesar+Chavez. You can see the names of our input fields,
recipient. You can also see the value of each input field to the right of an equals sign (my name is Diane and I'm writing to Cesar Chavez), and each input field is separated by an
&. PHP makes all of the information after the
? available inside of the
Remember the restaurant of the internet? When you submit a form, you are giving your lunch order to the waiter. All of the information in your lunch order is included in that one variable called
$_GET. Back in the kitchen, the PHP pastry chef can use the information in
$_GET to cook you up a custom web page.
Lastly, instead of signing the letter with my name, we will replace that with the variable
$my_name. Here's what the final version should look like:
<?php $friend_name = $_GET["recipient"]; $my_name = $_GET["sender"]; ?> <!DOCTYPE html> <html> <head> <title>Greetings!</title> </head> <body> <h1>Greetings From Afar</h1> <p>Dear <?php echo $friend_name ?>,</p> <p>How are you? I hope that you are having a nice weekend. I'm vacationing in the mountains of Tibet while I learn programming! </p> <p><?php echo $friend_name ?>, you would not believe how cold it is here. I should have gone to Hawaii instead. But I like programming a lot, so I've got that going for me. </p> <p>Looking forward to seeing you soon, I'll bring you back a souvenir. </p> <p>Cheers,</p> <p><?php echo $my_name ?></p> </body> </html>
Note: You may notice, that the individual php commands
<? php echo 'something' ?> do not have a
; at the end of the line.
Good eye! We could add a semicolon here at the end, or we could leave it off - both are actually valid here. What?? It's true! The PHP documentation states that: "The closing tag of a block of PHP code automatically implies a semicolon; you do not need to have a semicolon terminating the last line of a PHP block." Because these individual commands are all "last lines" we can use the semi here, or leave it off. Whether you do so or not is up to you - Just don't forget to always use a semicolon at the end of each statement in a multiline block!
Let's look at another example of a form: a Mad Lib! Mad Libs are an old game where you get to fill in the blanks in a story using parts of speech like nouns, verbs, etc. to turn it into something wacky and fun. So here is my form, saved to my document root as
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"> <title>A fantastical adventure</title> </head> <body> <div class="container"> <h1>Fill in the blanks to write your story!</h1> <form action="madlib_story.php"> <div class="form-group"> <label for="person1">A name</label> <input id="person1" name="person1" class="form-control" type="text"> </div> <div class="form-group"> <label for="person2">Another name</label> <input id="person2" name="person2" class="form-control" type="text"> </div> <div class="form-group"> <label for="animal">An animal</label> <input id="animal" name="animal" class="form-control" type="text"> </div> <div class="form-group"> <label for="exclamation">An exclamation</label> <input id="exclamation" name="exclamation" class="form-control" type="text"> </div> <div class="form-group"> <label for="verb">A past tense verb</label> <input id="verb" name="verb" class="form-control" type="text"> </div> <div class="form-group"> <label for="noun">A noun</label> <input id="noun" name="noun" class="form-control" type="text"> </div> <button type="submit" class="btn">Show me the story!</button> </form> </div> </body> </html>
Now I'm going to create the file
madlib_story.php in the same folder. This will contain the story that we are filling in, and we will use variables in our story to hold the user's choices for two names, an animal, an exclamation, a past tense verb and a noun.
<?php $person1 = $_GET["person1"]; $person2 = $_GET["person2"]; $animal = $_GET["animal"]; $exclamation = $_GET["exclamation"]; $verb = $_GET["verb"]; $noun = $_GET["noun"]; ?> <!DOCTYPE html> <html> <head> <title>Mad Lib</title> </head> <body> <h1>A fantastical adventure</h1> <p>One day, <?php echo $person1 ?> and <?php echo $person2 ?> were walking through the woods, when suddenly a giant <?php echo $animal ?> appeared. </p> <p>"<?php echo $exclamation ?>", <?php echo $person1 ?> cried. </p> <p>The two of them <?php echo $verb ?> as quickly possible, and when they were safe, <?php echo $person1 ?> and <?php echo $person2 ?> gave each other a giant <?php echo $noun ?>.</p> </body> </html>