Chapter 2. PHP Syntax: Weird and Wonderful

You’ve got a couple of PHP programs running, and one of them even works with an HTML form. But so far, you’ve just been typing code. Even though you’ve just gotten started with PHP, you’re ready to dig deeper, and start to understand what’s going on in that code. In this chapter, you’re going to get comfortable with a lot of the PHP syntax: that means learning what special words you type into your programs, and what each one of those special words—usually called keywords—tells PHP to do.

Fortunately, this learning doesn’t mean you can’t still build interesting programs that run in a web browser. In fact, since almost everything that’s done with PHP involves Web pages, all your scripts in this chapter will accept information from a Web form and work with that information. So you’re not just learning PHP; you’re learning to write Web applications.

Get Information from a Web Form

In sayHelloWeb.php, you used this line to get the value of a variable called “name” from the sayHello.html web form:

echo $_REQUEST['name'];

You may remember that $_REQUEST is a special PHP variable that lets you get information from a web request. You used it to get one particular piece of information—the user’s name—but it can do a lot more.

Access Request Parameters Directly

In fact, to see just how handy $_REQUEST really is, open up your text editor. Type the code below, in which a visitor enters her name and several other important bits of contact information, like her Twitter handle, Facebook page URL, and email address.

<html>
 <head>
  <link href="../css/phpMM.css" rel="stylesheet" type="text/css" />
 </head>

 <body>
  <div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
  <div id="example">Example 2-1</div>

  <div id="content">
    <h1>Join the Missing Manual (Digital) Social Club</h1>
    <p>Please enter your online connections below:</p>
    <form action="scripts/getFormInfo.php" method="POST">
         <fieldset>
        <label for="first_name">First Name:</label>
        <input type="text" name="first_name" size="20" /><br />
        <label for="last_name">Last Name:</label>
        <input type="text" name="last_name" size="20" /><br />
        <label for="email">E-Mail Address:</label>
        <input type="text" name="email" size="50" /><br />
        <label for="facebook_url">Facebook URL:</label>
        <input type="text" name="facebook_url" size="50" /><br />
        <label for="twitter_handle">Twitter Handle:</label>
        <input type="text" name="twitter_handle" size="20" /><br />
      </fieldset>
      <br />
      <fieldset class="center">
        <input type="submit" value="Join the Club" />
        <input type="reset" value="Clear and Restart" />
      </fieldset>
    </form>
  </div>

  <div id="footer"></div>
 </body>
</html>

Tip

For more information on how HTML is used in this code, see the box below.

Save this file as socialEntryForm.html. To make sure your HTML is just the way you want, go ahead and upload it to your server, in the ch02/ directory. Make sure you’ve got the book’s CSS in the right place—under css/ in your server’s root—and then open a browser and head over to your HTML form. You should see something like Figure 2-1.

In sayHelloWeb.php, you used $_REQUEST to get submitted form information, and then asked specifically for the “name” value. But with this new form, there’s a lot more information being sent from the form.

To get all that information, you need to create a new script called getFormInfo.php, and enter in this code:

<html>
 <head>
  <link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
 </head>

 <body>
  <div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
  <div id="example">Example 2-1</div>

  <div id="content">
    <p>Here's a record of what information you submitted:</p>
    <p>
      First Name: <?php echo $_REQUEST['first_name']; ?><br />
      Last Name: <?php echo $_REQUEST['last_name']; ?><br />
      E-Mail Address: <?php echo $_REQUEST['email']; ?><br />
      Facebook URL: <?php echo $_REQUEST['facebook_url']; ?><br />
      Twitter Handle: <?php echo $_REQUEST['twitter_handle']; ?><br />
    </p>
  </div>

  <div id="footer"></div>
 </body>
</html>
This web form is a pretty typical entry page for a user to fill in. But what happens when this form gets submitted? You’re about to find out, and in fact, take control of all this entered information.
Figure 2-1. This web form is a pretty typical entry page for a user to fill in. But what happens when this form gets submitted? You’re about to find out, and in fact, take control of all this entered information.

Note

If you want to start taking a little more control of your scripts, you can name this program something other than getFormInfo.php. Just be sure that you also update socialEntryForm.html and change the form’s action attribute value to match your own custom script name.

You can already see what’s going on here. In addition to grabbing the value of the “first_name” and “last_name” fields—similar to getting the value of the “name” field in sayHelloWeb.php—you’re using $_REQUEST to pull in the values the user entered into the other form fields.

Go back to your web form, and enter your information. Then submit the form, and you should see the result of getFormInfo.php running. Your browser should show you something like Figure 2-2.

In fact, this is the way you’ll use the $_REQUEST variable in most of your PHP programs:

echo $_REQUEST['FORM_INPUT_FIELD_NAME'];
Almost everything in PHP begins with some piece of information submitted via either an HTML Web form or another PHP script.
Figure 2-2. Almost everything in PHP begins with some piece of information submitted via either an HTML Web form or another PHP script.

Create Your Own Variables

You may have times where you don’t want to just spit out the value of a field. Think back to your first program, sayHello.php (the version that didn’t run on the Web). In that program, you created your own variable:

$name = trim(fgets(STDIN));

PHP lets you create all the variables you want. Just think of a descriptive name (for suggestions, see the box on What’s in a Name? A Whole Lot!), and put a dollar sign before that name, like this:

$numberSix = 6;
$thisIsMyName = "Brett";
$carMake = "Honda";

With this chunk of code in mind, go back to your new program, getFormInfo.php. Instead of just using echo to print out the submitted information, store each piece of information in a variable. Then you can use that information however you want, and as many times as you want.

<?php

$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
$facebook_url = $_REQUEST['facebook_url'];
$twitter_handle = $_REQUEST['twitter_handle'];

?>

<html>
 <head>
  <link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
 </head>

 <body>
    <!-- Existing HTML code -->
  </body>
</html>

Notice that you can create blocks of PHP code—beginning with <?php and ending with ?>—anywhere you want. In this script, there’s currently a block of PHP before any HTML, and then several small blocks of PHP within the big chunk of HTML. It’s really up to you when and where your PHP goes, as long as it gets the job done. You could have put this block of PHP between the page’s opening html and head element, or between the head and the body elements; that choice is up to you.

Note

Just because you can do something doesn’t mean you should. It’s usually best to do as much of your PHP work as you can before you output any HTML, and then output as much of your HTML as you can in a single place. This system keeps most of your code in one place, and most of your HTML in another place. (For more advice on why it’s important to keep your code well organized, see the box on Refactor as You Go.)

Of course, you’ll still have lots of times when you insert PHP into your HTML, as in getFormInfo.php, and that’s okay. Those little bits of PHP fit into the HTML, and certainly don’t mix things up as much as 20 or 30 lines of PHP stuck in the middle of your HTML.

You can check out your form in a browser, but you shouldn’t see anything different from what you already saw, shown back in Figure 2-2. That’s because your HTML—the part of the script that the browser displays to a user—hasn’t changed at all.

But now there’s a little bit of wasteful programming going on. You’re getting the value of each form field through the $_REQUEST variable once, in the PHP block before all your HTML, and then you’re getting all those variable values again in the HTML itself. Anytime you’re doing something twice, you’re wasting valuable web server resources.

Fortunately, it’s easy to fix this problem. You have all the values you want, stored in your variables: $first_name, $last_name, and so on. So in the HTML part of get-FormInfo.php, you can just echo out those variables; you don’t need to deal with $_REQUEST anymore. Here’s the “content” div you’ll want to update:

<div id="content">
  <p>Here's a record of what information you submitted:</p>
  <p>
    First Name: <?php echo $first_name; ?><br />
    Last Name: <?php echo $last_name; ?><br />
    E-Mail Address: <?php echo $email; ?><br />
    Facebook URL: <?php echo $facebook_url; ?><br />
    Twitter Handle: <?php echo $twitter_handle; ?><br />
  </p>
</div>

You should submit values into your socialEntryForm.html again, and make sure your updated script works. You should see the exact same result as before (compare your results to Figure 2-2 again). It may surprise you that you’ve done all this work just to get the same result; but that’s actually a big part of good programming. To learn more about this approach to programming, see the box below. This version has all the submitted values in variables, though, and that’s an improvement.

But why put values into a variable? Right now, it may seem a little silly: all you’re doing is changing the place within your script where you grab information from the $_REQUEST variable. That’s not doing you any real good. So what can you do with these variables once you’ve got information in them? PHP gives you a lot of options, particularly when you have variables with text in them.

Working with Text in PHP

PHP sees all text the same: as just a collection of characters. Those characters can be letters, numbers, spaces, punctuation marks, or just about anything else. And in PHP, an English word like “caterpillar” is just as ordinary a piece of text as is something nonsensical like “!(gUHa8@m.@”. To you, the first looks like a word, and the second like something QBert might have said. To PHP, though, it’s all just text. In fact, PHP and most programming languages have a special word to refer to text, since it’s such an important part of the language: a string. So a piece of text can also be called a string, and instead of text searching or text matching, you’ll often hear programmers talk about string searching or string matching.

Note

If you don’t need to Google QBert to find out what it is, take a moment to weep for your lost youth.

Combining Text

The good thing about PHP seeing all text the same is that you can do all sorts of interesting things with it, regardless of what that text is. So going back to your script, getFormInfo.php, you’ve got five variables, all of which are filled with text:

$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
$facebook_url = $_REQUEST['facebook_url'];
$twitter_handle = $_REQUEST['twitter_handle'];

Two of these are related: $first_name and $last_name. It’s pretty common to take in information this way—with the names separated—but it’s just as uncommon to print them out separately. Imagine walking into your local Pier 1 Imports and being greeted by an old friend like this: “Hey there, First Name Brett, Last Name McLaughlin!” That’s pretty awkward; and it’s just as awkward on the Web.

There’s no reason to settle for this separation, though. You can easily combine these two strings by using what’s called concatenation. That’s a fancy word that just means “combine,” and in the case of strings in particular, combining two pieces of text end-to-end. So if you concatenate “my” and “girl”, you’d get a new string, “mygirl.”

In PHP, you concatenate with the period (.). In getFormInfo.php, then, find the two lines of HTML where you print out the first and last name:

First Name: <?php echo $first_name; ?><br />
Last Name: <?php echo $last_name; ?><br />

Now change these to a single line, and concatenate the first and last names together:

Name: <?php echo $first_name . $last_name; ?><br />

Go back to socialEntryForm.html, enter some information, and submit your form. You should see something like Figure 2-3.

That’s all there is to it! Of course, there’s a pretty obvious problem here: the first name and last name are smashed together. What you really need is a space between those two bits of text.

Here’s where PHP treating all text the same really helps. You can add a space by simply putting it in quotes, like this: " ". PHP doesn’t see that text as any different from the text in your variables. So you can just concatenate that string—the empty space—to $first_name, and then $last_name to that:

Name: <?php echo $first_name . " " . $last_name; ?><br />

Try your form out again, and you should see a nice space between the first and last names. Check out Figure 2-4, which should match what your page now looks like.

One of the easiest ways to get your users comfortable with your web applications is to use plain English whenever possible. Even something as simple as combining first and last names adds a lot of familiarity to an otherwise cold web form.
Figure 2-3. One of the easiest ways to get your users comfortable with your web applications is to use plain English whenever possible. Even something as simple as combining first and last names adds a lot of familiarity to an otherwise cold web form.
PHP doesn’t care if text is in a variable like $_REQUEST, a variable you’ve created yourself, or in quotes. It treats all text exactly the same.
Figure 2-4. PHP doesn’t care if text is in a variable like $_REQUEST, a variable you’ve created yourself, or in quotes. It treats all text exactly the same.

Searching Within Text

If all you could do with strings was to smash them together, that would be pretty boring. Thankfully, PHP gives you a lot more. One of the most common things you’ll do with PHP text is search it. For example, take the $facebook_url variable you’ve got. Suppose you wanted to turn that into an actual link that people could click on:

<p>
  Name: <?php echo $first_name . " " . $last_name; ?><br />
  E-Mail Address: <?php echo $email; ?><br />
  <a href="<?php echo $facebook_url; ?>">Your Facebook page</a><br />
  Twitter Handle: <?php echo $twitter_handle; ?><br />
</p>

Now, instead of just showing the text of the URL, it’s turned into an actual clickable link, like in Figure 2-5.

Your PHP is not just a place for programming. It’s also a place to create parts of web pages. So when you get a URL or an email link, you should try and turn those into HTML links whenever possible.
Figure 2-5. Your PHP is not just a place for programming. It’s also a place to create parts of web pages. So when you get a URL or an email link, you should try and turn those into HTML links whenever possible.

But what happens if folks forget to put the facebook.com part of the URL in? Maybe they didn’t read carefully, and they just threw in the part of the URL after facebook.com, like ryan.geyer or profile.php?id=699186223. Then, the link you create won’t be of any use.

What you need, then, is a way to see if the text you’ve got in your $facebook_url variable contains facebook.com. If so, then it’s probably safe to turn the text into a URL link. But if not, the link probably needs to have http://www.facebook.com added to the beginning of the variable’s value.

The easiest way to do this in PHP is to look for the position of a piece of text inside a bigger piece of text. So you can see what the position of facebook.com is inside of $facebook_url, like this:

$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
$facebook_url = $_REQUEST['facebook_url'];
$position = strpos($facebook_url, "facebook.com");
$twitter_handle = $_REQUEST['twitter_handle'];

The strpos() function, which just stands for “string position,” returns a number that tells you where in the search string the searched-for text exists. So if $position was 5, that would mean that facebook.com appeared at position 5 within $facebook_url. (And if you’re wondering why that’s 5 and not 6, see the box on the next page.)

But it’s not enough to just get a position. You need to do something with it. Better, you need to figure out if it indicates a position within $facebook_url—which would mean that $facebook_url contains “facebook.com”—or if $facebook_url doesn’t have facebook.com within it at all. You can do this by seeing if $position is false, something PHP defines for you using the keyword false. Otherwise, strpos() returns the position within $facebook_url where the searched-for string appears.

Note

strpos(), like most functions in PHP, can return two totally different things: a number indicating a position within the search string, or the value false.

$first_name = $_REQUEST['first_name'];
$last_name = $_REQUEST['last_name'];
$email = $_REQUEST['email'];
$facebook_url = $_REQUEST['facebook_url'];
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
  $facebook_url = "http://www.facebook.com/" . $facebook_url;
}
$twitter_handle = $_REQUEST['twitter_handle'];

At first glance, it probably looks like there’s a lot of new stuff going on here, but don’t sweat it. You already understand almost all this code.

  1. First, strpos() is used to see if $facebook_url has facebook.com within it. The value returned from strpos() is stuffed into a new variable, $position.

  2. $position is compared to the special PHP value false using an if statement. You’ll learn a lot more about if statements soon, but it does just what it looks like: if $position is false, then do the code within the curly brackets, { }.

  3. The code that’s within { } only gets run if the statement above is true—in this case, if $position === false. If that’s true, then $facebook_url gets http://www.facebook.com smashed onto the front, to make a real link to Facebook.

  4. This is really a hidden step: if $position is not false, then nothing happens. The line of code within { } gets completely skipped over.

Now that you’ve got your changes made to your script, save it, and go back to your web form, socialEntryForm.html. This time, enter in a Facebook link without the facebook.com part of the URL, like profile.php?id=100000039185327. Then submit your form and see what your result looks like.

At first glance, nothing may look different. Your web page generated from your PHP probably still resembles Figure 2-5. But look at the source of your page (shown in Figure 2-6) or click the link itself (shown in Figure 2-7). In both cases, you can see that profile.php?id=100000039185327 was turned into an actual URL, http://www.facebook.com/profile.php?id=100000039185327.

If you’ve not done a lot of web development, you may not be used to looking at your web page’s source code. But you’ll want to get comfortable viewing the source; it’s one of your best ways to see what’s really in the HTML your scripts generate.
Figure 2-6. If you’ve not done a lot of web development, you may not be used to looking at your web page’s source code. But you’ll want to get comfortable viewing the source; it’s one of your best ways to see what’s really in the HTML your scripts generate.
It may seem like a small thing—and a lot of work—to take a partial URL and make it into a clickable link. But users are forgetful, and the more you can protect them from making a mistake without telling them about their problems, the better.
Figure 2-7. It may seem like a small thing—and a lot of work—to take a partial URL and make it into a clickable link. But users are forgetful, and the more you can protect them from making a mistake without telling them about their problems, the better.

Changing Text

You’ve combined two pieces of text, you’ve searched within text, so what’s left? Well, changing text, of course. And it turns out that you’ve already got a lot of the pieces you need to change text.

Take for example the Twitter handle people are entering into your web form. Most people put an @ before their Twitter handle, like this: @bdmclaughlin. But to see someone’s Twitter profile on Twitter.com, you actually don’t want that @. So if your Twitter handle is @phpGuy, then the Twitter URL to see your profile would be http://www.twitter.com/phpGuy.

This means that to turn a Twitter handle into a clickable link, you have to take a few steps:

  1. Create a new variable, $twitter_url, and start by giving it a value of “http://www.twitter.com/”.

  2. Figure out of the Twitter handle has an @ sign in it.

  3. If there’s no @ in $twitter_handle, just add the handle to the back of $twitter_url.

  4. If there is an @ in $twitter_handle, remove the @ from the handle, and add the handle to the end of $twitter_url.

  5. Display the Twitter handle as part of an <a> link element in your script’s HTML output.

You’ve done something similar to all these steps except for 4, so this program shouldn’t be a big problem for you.

First, create a new variable to hold the Twitter URL you’re building, and give it the first part of the Twitter URL:

$twitter_handle = $_REQUEST['twitter_handle'];
$twitter_url = "http://www.twitter.com/";

Then, you need to figure out if the Twitter handle—which you’ve got in the $twitter_handle variable—has the @ character anywhere in it. You can use strpos() again for this:

$twitter_handle = $_REQUEST['twitter_handle'];
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");

In this case, you have to do something whether there’s an @ in $twitter_handle or not. So you’ll have an if, but also an else:

$twitter_handle = $_REQUEST['twitter_handle'];
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
  $twitter_url = $twitter_url . $twitter_handle;
} else {
  // Do something to remove the @ from the Twitter handle
}

This should make perfect sense. If there’s no @, just add the handle to the end of $twitter_url. If there is an @, you’ve got more work to do.

You’ve already seen that strpos() takes a string, and then another string to search for. PHP has a similar way to get just part of a string: substr(). substr() is short for “substring,” which just means a part of a string. You give substr() a string, and then a position to start at.

So substr(“Hello”, 2) would give you “llo”. That’s because the “H” is at position 0, the “e” is at position 1, and the first “l” is at position 2. Since you gave substr() 2 as the position at which to start, you get the letters from that position to the end of the string: “llo”.

Warning

Remember, most PHP functions like substr() and strpos() start counting at zero. If you’re still unsure about how that works, check out the box on Programming Languages Like Zeroes.

In the case of the Twitter handle, you can use substr() in a similar way. But you want to cut off everything up to and including the @ sign, which you already know is at the position stored in $position. So you can use substr(), and start your new string at the position after $position, or $position + 1.

$twitter_handle = $_REQUEST['twitter_handle'];
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
  $twitter_url = $twitter_url . $twitter_handle;
} else {
  $twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}

Note

You’re starting to see a lot of new code quickly, but don’t worry if something confuses you at first glance. Just take a moment and look at each piece of the new code, bit by bit. As you understand each individual piece, you’ll find the overall picture becomes really clear pretty fast.

Now all that’s left is to update the part of your script that outputs HTML:

<p>
  Name: <?php echo $first_name . " " . $last_name; ?><br />
  E-Mail Address: <?php echo $email; ?><br />
  <a href="<?php echo $facebook_url; ?>">Your Facebook page</a><br />
  <a href="<?php echo $twitter_url; ?>">Check out your Twitter feed</a><br />
</p>

Hop back to your entry page, fill it up with information, and then submit the form to your updated script. Try it with and without an @ in your Twitter handle, and the results should be the same: a nice output page with links to your Facebook and Twitter page, with the @ correctly removed (see Figure 2-8).

You may want to update your PHP script even further, to add some additional style and formatting. You may want to change things to read from your user’s perspective: “My name,” and “Check out my Twitter page.” Don’t be afraid to experiment, now that you’re getting comfortable with your PHP script.
Figure 2-8. You may want to update your PHP script even further, to add some additional style and formatting. You may want to change things to read from your user’s perspective: “My name,” and “Check out my Twitter page.” Don’t be afraid to experiment, now that you’re getting comfortable with your PHP script.

Trimming and Replacing Text

Once you start trying to help your users out with possible errors in their form entry, the world of PHP strings becomes a big toolkit at your disposal. Take two other common problems in web forms, especially web forms where users enter URLs:

Note

You’d be pretty surprised how often people mix up .com and .org. In fact, lots of companies that own domain-name.com will also buy domain-name.org and redirect anyone that goes to domain-name.org to domain-name.com, just because of this common problem.

You now how PHP strings work, and you’ve already used several PHP functions, so you just need to learn two more to handle these common problems.

Remove Extra White Space with trim()

PHP’s trim() function ditches any empty characters—what PHP calls white space—around a string. So trimming “ I love my space bar. ” gives you “I love my space bar.” So with just a couple of simple additions to your script, you can make sure that extra spaces around your users’ entries is a thing of the past:

Note

PHP also gives you rtrim(), which trims just white space after a string (on its right side), and ltrim(), which trims whitespace before a string (on its left side).

$first_name = trim($_REQUEST['first_name']);
$last_name = trim($_REQUEST['last_name']);
$email = trim($_REQUEST['email']);
$facebook_url = trim($_REQUEST['facebook_url']);
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
  $facebook_url = "http://www.facebook.com/" . $facebook_url;
}

$twitter_handle = trim($_REQUEST['twitter_handle']);
$twitter_url = "http://www.twitter.com/";
$position = strpos($twitter_handle, "@");
if ($position === false) {
  $twitter_url = $twitter_url . $twitter_handle;
} else {
  $twitter_url = $twitter_url . substr($twitter_handle, $position + 1);
}

The change is simple: every time you get a value from $_REQUEST, just wrap the value in trim(). You’ll never have to worry about white space around your text again.

Warning

trim() (as well as rtrim() and ltrim()) remove only white space on the outside of your text. So trim() is great for dealing with something like “ Way too much white space. ” but won’t help you at all with “Way too much white space.”

Replace Characters in Text with str_replace()

It’s also easy to replace text in a string. You use str_replace(), and give it three things:

  1. The text to search for. So if you’re looking for facebook.org, the search text would be “facebook.org”.

  2. The replacement text. So if you want to replace every occurrence of facebook. org with facebook.com, your replacement text would be “facebook.com”.

  3. The string in which to search. In this case, the value the user types into your web form.

Put it all together, and you’ll get something like this:

$facebook_url = str_replace("facebook.org", "facebook.com",
                            trim($_REQUEST['facebook_url']));
$position = strpos($facebook_url, "facebook.com");
if ($position === false) {
  $facebook_url = "http://www.facebook.com/" . $facebook_url;
}

Note

For more information on why that str_replace() looks the way it does, see the box on Chain Your Methods (Or Not!).

Make these changes, and then visit your web form again. Enter some information that might have been a problem for a less-skilled PHP programmer, with lots of spaces and a bad facebook.org URL, like in Figure 2-9.

You’d be amazed at how often people fill out forms in a hurry. That usually means one of two things will happen: either all that problematic information causes errors in a server-side script, or—if the programmer is a little more advanced—the script happily fixes those errors and keep on chugging. It’s good to be in the second category!
Figure 2-9. You’d be amazed at how often people fill out forms in a hurry. That usually means one of two things will happen: either all that problematic information causes errors in a server-side script, or—if the programmer is a little more advanced—the script happily fixes those errors and keep on chugging. It’s good to be in the second category!

Submit this data, and you’ll see in Figure 2-10 that getFormInfo.php doesn’t miss a beat. It gets rid of all that extra space, and even fixes the bad Facebook URL (see Figure 2-11).

Using trim() and str_replace() and even strpos() is part of being a responsible PHP programmer. In fact, you may eventually build your own standard blocks of code that you run all your web form entries through, just to make sure they’re formatted just the way you like.
Figure 2-10. Using trim() and str_replace() and even strpos() is part of being a responsible PHP programmer. In fact, you may eventually build your own standard blocks of code that you run all your web form entries through, just to make sure they’re formatted just the way you like.
Once again, View Source is your friend. In most browsers, this option is under the View menu, the Page menu, or available by rightclicking on your page. Make sure you can view your page’s source; it’s what’s really getting sent to the browser, no matter how things actually look on your screen.
Figure 2-11. Once again, View Source is your friend. In most browsers, this option is under the View menu, the Page menu, or available by rightclicking on your page. Make sure you can view your page’s source; it’s what’s really getting sent to the browser, no matter how things actually look on your screen.

The $_REQUEST Variable

PHP is a lot more than a way to work with text. You’ve been working with strings non-stop, but there are a lot more types of information you’ll need to work with in your PHP scripts. As you might expect, there are all kinds of ways to work with numbers, and you’ll work with numbers quite a bit before long.

But there’s another really important type of information you need to understand; in fact, you’ve already been working with this type, as much as you’ve worked with text. This mystery type is an array: a sort of container that actually holds other values within it.

Arrays Can Hold Multiple Values

An array is a type of data structure. That’s one of those terms that will gain you respect at a Google get together, but might get you some odd looks if you’re having cocktails at a political fundraiser. But arrays aren’t actually that hard to understand. Think of an array as a file cabinet of information, and you’ve got the idea.

So if you have a variable called, for example, $file_cabinet, that’s an array, and it can store other information within it. You can stuff URLs, and first and last names, email addresses, and so on into that $file_cabinet. You fill up the file cabinet by telling PHP where you want your information using numbers in square brackets, right after the array variable name, like this:

<?php

$file_cabinet[0] = "Derek";
$file_cabinet[1] = "Trucks";
$file_cabinet[2] = "[email protected]";
$file_cabinet[3] = "http://www.facebook.com/DerekTrucks";
$file_cabinet[4] = "@derekandsusan";

?>

These numbers are like drawers in the file cabinet, or if you like things a little more compact, labels on file folders within the cabinet.

Note

Any time you see a code example like this, you can type it, save it (using a name like file_cabinet.php), and run it with the php command. Go ahead and try it…you’ll be changing things and making up your own programs in no time.

Then, you can get information out of $file_cabinet by using those same numbers within brackets:

$first_name = $file_cabinet[0];
$last_name = $file_cabinet[1];
$email = $file_cabinet[2];
$facebook_url = $file_cabinet[3];
$twitter_handle = $file_cabinet[4];

Warning

It’s probably old hat to you by now, but remember that most things in PHP start counting at 0 (see the box on Programming Languages Like Zeroes). Arrays are no different. So the first item in $file_cabinet is $file_cabinet[0], not $file_cabinet[1].

And then you can do whatever you want with those values, including print them out. Here’s a complete program that isn’t very useful, but certainly puts an array through its paces. It fills an array, pulls information out of the array, and then does a little printing.

<?php

$file_cabinet[0] = "Derek";
$file_cabinet[1] = "Trucks";
$file_cabinet[2] = "[email protected]";
$file_cabinet[3] = "http://www.facebook.com/DerekTrucks";
$file_cabinet[4] = "@derekandsusan";

$first_name = $file_cabinet[0];
$last_name = $file_cabinet[1];
$email = $file_cabinet[2];
$facebook_url = $file_cabinet[3];
$twitter_handle = $file_cabinet[4];

echo $first_name . " " . $last_name;
echo "
Email: " . $email;
echo "
Facebook URL: " . $facebook_url;
echo "
Twitter Handle: " . $twitter_url;
?>

Now, this is helpful—who doesn’t like to file things away for use later?—but there’s a bit of a problem here. Who’s going to remember that at position 2, you’ve got a last name, and at position 4, you’ve got the Facebook URL? That’s a disaster waiting to happen.

Fortunately, the wise folks that came up with PHP thought this through. PHP arrays are associative, which means you can associate labels with each item in the array. So going back to the idea of each number being a folder in a file cabinet, you can use an actual label on the folder. Better yet, that label can be anything you want.

So here’s that same simple program; but this time it uses associative labels. You should make these changes to your own copy of this script if you’re following along.

<?php

$file_cabinet['first_name'] = "Derek";$file_cabinet['last_name'] = "Trucks";
$file_cabinet['email'] = "[email protected]";
$file_cabinet['facebook_url'] = "http://www.facebook.com/DerekTrucks";
$file_cabinet['twitter_handle'] = "@derekandsusan";

$first_name = $file_cabinet['first_name'];
$last_name = $file_cabinet['last_name'];
$email = $file_cabinet['email'];
$facebook_url = $file_cabinet['facebook_url'];
$twitter_handle = $file_cabinet['twitter_handle'];

echo $first_name . " " . $last_name;
echo "
Email: " . $email;
echo "
Facebook URL: " . $facebook_url;
echo "
Twitter Handle: " . $twitter_url;
?>

By now, though, this $file_cabinet should be looking a bit familiar. You’ve seen something that looks awfully similar…

Working with $_REQUEST as an Array

This special variable PHP gave you with all the information from a web form, called $_REQUEST, is also an array. And when you’ve written code like $_REQUEST[‘first_name’], you’ve just been grabbing a particular piece of information out of that array.

In fact, you’ve already seen that the most powerful way to use arrays is really behind the scenes. You (or a web browser) sticks information into the array, and then you pull that information back out, and work with it. It really doesn’t matter that an array was involved; it’s just a convenient way to hold things, as when a browser is sending a request to your PHP script.

You’ve seen that you can not only get to information in an array by a name—the label on a file folder—but by number (The $_REQUEST Variable). So you can do $file_cabinet[‘first_name’], but you can also do $file_cabinet[0]. The same is true of $_REQUEST; it’s just an array, so doing $_REQUEST[0] is perfectly OK with PHP.

So what exactly is in $_REQUEST? Go ahead and create a new program, and you can see for yourself.

<html>
 <head>
  <link href="../../css/phpMM.css" rel="stylesheet" type="text/css" />
 </head>

 <body>
  <div id="header"><h1>PHP & MySQL: The Missing Manual</h1></div>
  <div id="example">Example 2-2</div>

  <div id="content">
    <p>Here's a record of everything in the $_REQUEST array:</p>
    <?php
      foreach($_REQUEST as $value) {
        echo "<p>" . $value . "</p>";
      }
    ?>
  </div>

  <div id="footer"></div>
 </body>
</html>

Here’s another one of those scripts that may look intimidating at first, but it’s really not bad at all. In fact, the only thing you’ve not seen before is the line with the foreach keyword, which you’ll get into a lot more a bit later. For now, take a closer look at this line, which begins a PHP loop:

foreach($_REQUEST as $value) {

foreach is a nifty PHP creation that lets you quickly get at the values of an array. In this case, foreach takes an array—$_REQUEST—and then pulls each value out of that array, one at a time. Each time it pulls out a single value, it assigns that value to a new variable called $value; that’s the as $value part of the foreach line. So inside the foreach loop, you’ll have a $value variable that has a single value within the array.

Just as in the if statement you’ve used a few times, the curly braces—{ }—tell PHP where the beginning and the end of this loop are:

foreach($_REQUEST as $value) {
  echo "<p>" . $value . "</p>";
}

Everything between the { } runs once for each time through the loop. So that means that for every item in $_REQUEST, this line is going to run one time:

echo "<p>" . $value . "</p>";

This line shouldn’t be any big deal to you at all: it just prints out $value with some HTML formatting. But since each time through this loop, $value has a different value from $_REQUEST, it’s a quick way to print out every value in $_REQUEST.

Now suppose that $_REQUEST has values within it like Derek, Trucks, and @DerekAndSusan. When PHP runs your code, it ends up doing something like this:

echo "<p>" . "Derek" . "</p>";
echo "<p>" . "Trucks" . "</p>";
echo "<p>" . "@DerekAndSusan" . "</p>";

Save this script as showRequestInfo.php. You’ll also need to change where your socialEntryForm.php web form submits its information:

<form action="scripts/showRequestInfo.php" method="POST">
  <fieldset>
    <label for="first_name">First Name:</label>
    <input type="text" name="first_name" size="20" /><br />
    <label for="last_name">Last Name:</label>
    <input type="text" name="last_name" size="20" /><br />
    <label for="email">E-Mail Address:</label>
    <input type="text" name="email" size="50" /><br />
    <label for="facebook_url">Facebook URL:</label>
    <input type="text" name="facebook_url" size="50" /><br />
    <label for="twitter_handle">Twitter Handle:</label>
    <input type="text" name="twitter_handle" size="20" /><br />
  </fieldset>
  <br />
  <fieldset class="center">
    <input type="submit" value="Join the Club" />
    <input type="reset" value="Clear and Restart" />
  </fieldset>
</form>

Note

You may want to create a copy of socialEntryForm.html, and call it something else, like socialEntryForm-2.html or enterInformation.html. Then you can have two versions: one that sends information to showRequestInfo.php, and one that sends information to getFormInfo.php.

Now, visit your new web form, fill it out, and submit it. You’ll get a pretty interesting web form back: the result of running your new showRequestInfo.php script. This finally tells you what’s really being sent between your web browser and a web server, and you can see it all in Figure 2-12.

There are definitely some things that you expected here, like the information from your web form. But what about those strange numbers? To understand what those are, you need to gather more information from $_REQUEST.
Figure 2-12. There are definitely some things that you expected here, like the information from your web form. But what about those strange numbers? To understand what those are, you need to gather more information from $_REQUEST.

So now you have the raw information, but what does it all mean? These results are like seeing all the files on a computer, but having none of those files’ names. Or, if you like the file cabinet analogy, imagine having a cabinet of folders with all the labels torn off. It makes knowing what’s going on a little trickier.

With the form data, you already know the labels: first_name, last_name, email, and so on. In an associative array like PHP uses, these are called the keys. So you can get the value of a particular “folder” in an array with code like this:

$value = $file_cabinet[$key];

This code gets the value from the array that’s attached to whatever label the $key variable holds. If $key was first_name, then the code would basically be the same as this:

$value = $file_cabinet['first_name'];

So in showRequestInfo.php, you just need to also get the keys from the $_REQUEST array, instead of just the values. Then you can print out both the key and the value. And, wouldn’t you know it, PHP makes that easy, again with foreach:

<div id="content">
  <p>Here's a record of everything in the $_REQUEST array:</p>
  <?php
    foreach($_REQUEST as $key => $value) {
      echo "<p>For " . $key . ", the value is '" . $value . "'.</p>";
    }
  ?>
</div>

This time, you’re telling foreach to get both the key, as $key, and the value, as $value. That special => sign tells PHP you want the $key and then the $value attached to the key. In other words, you’re grabbing a label and the folder that label is attached to, which is just what you want.

Fill out your form one more time, and check out the results of your updated PHP script, shown in Figure 2-13.

Finally, the secret of those weird numbers is revealed: they’re attached to some special keys called __utmz, __utma, and __utmc. You can also see your web forms labels: first_name, last_name, and the rest.
Figure 2-13. Finally, the secret of those weird numbers is revealed: they’re attached to some special keys called __utmz, __utma, and __utmc. You can also see your web forms labels: first_name, last_name, and the rest.

Note

You may see something similar to those weird things that $_REQUEST is storing: __utmz and __utmc, although that’s largely dependent on your web server and your hosting provider. They’re special HTTP variables that may get set by your server.

(These HTTP variables aren’t anything you need to worry about, but if you’re really interested, tweet @missingmanuals and tell them to get cracking on HTTP: The Missing Manual.)

What Do You Do with User Information?

At this point, you’ve got a lot of information stuffed into a lot of variables. In fact, your earlier web form, socialEntryForm.html, looks a lot like the signup forms you’ve probably filled out hundreds (or thousands!) of times online. But there’s a problem, isn’t there? In fact, you may have already run across it as you worked through all the changes to your getFormInfo.php script: none of that information ever got saved! You had to enter in your name and social information, over and over and over.

Good PHP programmers are able to solve just about any technical problem you throw at them. They know all the PHP string functions, they know about arrays, and a whole lot more. But great PHP programmers can solve a whole set of problems that those good PHP programmers never think about: user expectation problems. These are problems that really aren’t technical—although you might need to be a good programmer to work around users.

Here’s the million-dollar question: What does your user expect your pages and scripts to do? For instance, does your user expect to have to come back to your page and enter in the same information, over and over? Absolutely not. In fact, you’d probably stop visiting a site like that. So you’ve got a user expectation problem—and if you want users to hang around and use your site, you better solve this problem.

In fact, one of the best things you can do is actually use your own pages and programs. Get a cup of coffee, a notepad, and sit down at your computer. Close all your text editors and programming tools, and think, “I’m a user!” Then try out your web form, submit the form, enter weird information in, and see what happens. Take a few notes about things that bug you, but remember: you’re just a user here.

Tip

You may be tempted to make all your notes in a text editor, or just start fixing things. Resist this urge. As soon as you start fixing things, or even getting immersed in your computer, you’re not thinking like a user anymore, and you’ll miss things.

You’ll probably find all sorts of things you didn’t even think about. So now what? Well, you’ve got to start fixing those things. And first up is this pesky issue of having to enter the same information into your page, over and over.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.163.31