Lesson Weekend

Now that we've got a server running that can serve up pages, let's start writing some PHP. When working with PHP, we need a way to store information in our code - things like user names, product prices, and even geographical locations. To do this, we use variables. A variable is essentially a container for storing information.

To understand how variables work, let's pretend you're on vacation. Lucky you! But unfortunately, you have too many friends who all want to receive greeting cards from you. What's a programmer to do? You want to enjoy your vacation, not sit around writing letters. So let's write a program with PHP that will let us write one letter for all of them and then replace the names for each of your friends. Here's my first draft:

<!DOCTYPE html>
<html>
<head>
    <title>Greetings!</title>
</head>
<body>
    <h1>Greetings From Afar</h1>
    <p>Dear Jennifer,</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>Jennifer, 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>Diane</p>
</body>
</html>

Let's turn on the server and save this file as letter.html in our document root folder (where you started your server).

We're going to send this same letter to 3 of your other friends, Max, Beth and Robin, but we need to use their names instead of Jennifer's name.

In order to customize the letter, we'll need to do three things:

  1. Serve the page using the PHP server.
  2. Convert Jennifer's name from static HTML into PHP code.
  3. Change the PHP code to use variables, so that the name can easily be switched.

Let's convert it to PHP, so that we can easily change the name of the person we're addressing it to. To tell your server that you're going to be using PHP in this file, we'll first need to rename the file from letter.html to letter.php. Check that everything still looks the same by going to http://localhost:8000/letter.php.

Next, we'll print the name "Jennifer" using PHP instead of HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Greetings!</title>
</head>
<body>
    <h1>Greetings From Afar</h1>
    <p>Dear <?php echo "Jennifer"; ?>,</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 "Jennifer"; ?>, 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>Diane</p>
</body>
</html>

This isn't terribly useful yet, but bear with me. Let's break down the PHP code we've added to the page:

  • PHP code goes between the <?php and the ?>. These tags can be used anywhere in your HTML document, as many times as you like. Anything outside of these special tags will be interpreted as HTML.
  • We use a special word called echo to tell the PHP interpreter to print to the browser whatever is written next to it in quotes. Special words like echo that are built into a computer language are called keywords.
  • Finally, the code ends with a semicolon. Every line of PHP code must end with a semicolon - this is how the language knows we've reached the end of a command.

The final step to making our form letter is to use variables. Think of a variable like your lunchbox. Say you have labeled your lunchbox with your name so that no one at work steals it. Your lunchbox always contains some kind of food, but one day you might put a sandwich in it, and another day you might put leftover spaghetti in it. Like your lunchbox has a label and holds food, a variable has a name and holds information.

We can create a PHP variable in our letter above our HTML code, like this:

<?php 
    $friend_name = "Jennifer"; 
?>

<!DOCTYPE html>
<html>
<head>
    <title>Greetings!</title>
</head>
…

Then, we can use the variable in the rest of our letter by replacing the word “Jennifer” with it like this:

<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>Diane</p>
</body>

If you refresh the page in your browser, it should look exactly the same as before. But now, changing the name of the person in the form is as simple as switching this:

<?php 
    $friend_name = "Jennifer"; 
?>

to this:

<?php 
    $friend_name = "Max"; 
?>

or this:

<?php 
    $friend_name = "Beth"; 
?>

Try it out and see how it works in your browser!

To use a variable in PHP, there are 4 rules to remember:

  1. Variable names must begin with $. Just like the keyword echo was a signal meaning "print", the PHP language will recognize $ at the beginning of a word as a signal that this is the name of a variable: the label on our lunchbox.
  2. After the $, variable names must start with a lowercase letter.
  3. Variable names must only contain the letters a-z, A-Z, the characters 0-9 and _ (underscore).
  4. Variable names must not contain spaces.

Let's walk through one more example of using variables with PHP. Say you have to order supplies every month for the chain of coffee shops you own. Your business has several locations and they don't always need the same stuff every week. You have to send an order to the cup supplier and tell them that your downtown location needs 300 cups, the northwest location needs 500 cups, and the south location needs 1000. You also have to send an order to the coffee supplier and the dairy supplier and tell them what you need. Let's create a template for the orders using HTML, and then fill it in with some PHP.

Create a file called order_template.php and save it in the same document root folder as the previous example so that we don't have to restart the server. Now type this into it:

<!DOCTYPE html>
<html>
<head>
    <title>Order Form</title>
</head>
<body>
    <p>Hi Ed, </p>
    <p>Just making my weekly order. Details are below.</p>
    <p>300 Cups</p>
    <p>208 SW 5th Ave #105, Portland, OR 97204</p>
    <p>500 Cups</p>
    <p>1978 19th Ave, Portland, OR 97209</p>
    <p>1000 Cups</p>
    <p>1493 SW 2nd Ave, Portland, OR 97201</p>
    <p>Thanks,</p>
    <p>Diane</p>
</body>
</html>

Open the page in your browser at http://localhost:8000/order_template.php. So far we're only using HTML, but we can still use the .php extension on the file name - there's just nothing for the PHP interpreter to do yet. Using our restaurant metaphor, the PHP pastry chef is standing by because we named our file .php, but there’s no pastry in our recipe yet.

If you look at the details of the order that will have to change each time, we can see that we need seven variables here. One for "Ed" (who we're ordering from), one for the address of each store location and one for the amount of supplies for each location. We'll create the variables at the top of the file in PHP, and set them to default values from the template we wrote above. Type this into order_template.php above the <!DOCTYPE html> tag.

<?php 
    $recipient = "Ed";
    $downtown_address = "208 SW 5th Ave #105, Portland, OR 97204";
    $northwest_address = "1978 19th Ave, Portland, OR 97209";
    $south_address = "1493 SW 2nd Ave, Portland, OR 97201";
    $downtown_order = "300 Cups";
    $northwest_order = "500 Cups";
    $south_order = "1000 Cups";
?>

Next, we can replace these values in the body of the HTML part of our template with our variables. Now, it should look like this:

<body>
    <p>Hi <?php echo $recipient; ?>, </p>
    <p>Just making my weekly order. Details are below.</p>
    <p><?php echo $downtown_order; ?></p>
    <p><?php echo $downtown_address; ?></p>
    <p><?php echo $northwest_order; ?></p>
    <p><?php echo $northwest_address; ?></p>
    <p><?php echo $south_order; ?></p>
    <p><?php echo $south_address; ?></p>
    <p>Thanks,</p>
    <p>Diane</p>
</body>

If you open it in your browser, it should look the same because we used default values taken from our template.

Using these variables saves us from accidentally messing up a shipping address if we had to type all of them out by hand each time. Now every time we make an order, all we have to do is change the values of the three $x_order variables, and the $recipient variable. Try changing the values of the variables like this and then reload the page in your browser:

<?php 
    $recipient = "Jesse";
    $downtown_address = "208 SW 5th Ave #105, Portland, OR 97204";
    $northwest_address = "1978 19th Ave, Portland, OR 97209";
    $south_address = "1493 SW 2nd Ave, Portland, OR 97201";
    $downtown_order = "20 lbs dark roast, 15 lbs light roast.";
    $northwest_order = "50 lbs dark roast.";
    $south_order = "40 lbs light roast.";
?>

Lastly, here is a stylistic rule you should start practicing with your code. When using PHP, all of your code (including the HTML) should be indented by 4 spaces instead of 2 spaces. For example, you can see above that between the two <?php ?> tags every line of code is indented by 4 spaces. There are a few more stylistic rules we are going to introduce to you in these lessons, and while disobeying them may not break your code, there are good reasons to get in the habit of following them.

First, if you learn to write your code using these rules, it'll be easier to see where there's a problem. Also, if you get used to reading code using these styles you'll understand other people's code faster. Remember, even though PHP is a computer language, it is still a language, and you should try to look for patterns in it. When you started learning how to read English you had to sound out every letter in every word, but now you can just glance at a word or a sentence and immediately know what it means. Eventually you'll be able to do the same thing with PHP. Plus, no matter how brilliant your code is, potential employers looking at it will think it is bad if it is messy.