PHP and MySQL: The Missing Manual (2011)

Part 1. PHP and MySQL Basics

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.

POWER USERS’ CLINIC: HTML SHOULD BE SEMANTICALLY MEANINGFUL

You may have noticed some pretty big changes in this HTML from the simple form from Chapter 1 (Write a PHP Script). In that chapter, the form used <p> tags to break up the form labels and input boxes, and manually formatted the form labels with <i> tags. That got the job done, but it’s not a good use of HTML.

Anytime you’re writing HTML, you’re actually structuring your page. So a form tag doesn’t really do anything visually; it just lets a browser know, “Hey, here’s a form.” When you use tags like <i>, though, you’re not describing structure; you’re telling the browser how something should look. That’s really not what HTML is for, though; that’s the job of CSS.

In this form, though, all the formatting has been pulled out. Instead, all the labels are identified with the label element, and a for attribute. That identifies the labels as labels—regardless of how those labels end up looking—and also connects each label with the specific input field to which it matches. There’s also a fieldset element that surrounds the different blocks within the form: one for the labels and text fields, and a second for the form buttons. This arrangement also provides semantic information: information that has meaning.

By making the HTML mean something, a browser (and other HTML authors) know what things actually are in your form: labels are meant for, well, labeling things. Fields are grouped together with fieldset. And italic and bold are left to your CSS, just as they should be.

What’s really cool here is that now your CSS can do an even better job of styling your form. Since you’ve gotten rid of formatting in the HTML, you can style all your form labels the same way—perhaps by bolding them, right-aligning them, and adding a right margin of 5 pixels. The same is true of your sets of fields; you might put a border around related fields, which is exactly what’s going on in the CSS applied to this form. In fact, to see how the CSS affects these HTML elements, check out Figure 2-1.

Truthfully, if you’re new to making your pages semantically meaningful, it may take you a little time to get used to using HTML just for structure, and keeping all your style in CSS. But stick with it; your pages will look better, and anyone who has to update your pages down the line will thank you.

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>

WORD TO THE WISE: WHAT’S IN A NAME? A WHOLE LOT!

PHP doesn’t actually require you to use descriptive names. In fact, there are thousands of PHP programs on the Web with code that looks like this:

$x = $_REQUEST['username'];

$y = $_REQUEST['password'];

This code runs just as well as similar code that uses much more descriptive names:

$username = $_REQUEST['username'];

$password = $_REQUEST['password'];

So what’s the big deal? Many programmers will try and convince you that it’s a lot of extra work to type in these longer descriptive names. That’s true, of course.

On the other hand, imagine how much work it would be when you’ve got to track down the username variable in a piece of code that you wrote three months ago—or someone else wrote? Suppose you’ve got a line much later in a script like this:

echo "Welcome back to the site, " . $y;

Suddenly, it’s not so clear what $x is and what $y is. Was $x the username? Or was it $y? Better be careful…nobody wants his password printed out instead of his username!

Using descriptive names, even if they’re longer and take a little extra time to type, makes your code easier to read, for you and anyone else who might need to look at it down the road.

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.

WORD TO THE WISE: REFACTOR AS YOU GO

Any time you rearrange code, especially to better organize it, or separate different chunks of behavior, you’re refactoring. So when you created a PHP block at the beginning of getFormInfo.php to grab all the information from the submitted form, and then just echoed out each variable within the HTML, you were refactoring your script.

Refactoring should be as much as part of your routine as saving your files. Anytime you can better organize your script—or, as you’ll do later, better organize lots of scripts that all work together—do it. Even if you’re not sure how your better organization might help your program, it’s worth the effort. When you come back to your code a week from now, a month from now, or even a year from now, you’ll have a much harder time remembering what everything does. Even worse, it’s going to be tough to remember where things are in your script. (Your scripts are going to get a lot longer soon, too.)

By refactoring as you go, you ensure that it’s easy to see what a script does from a quick look. It also means that when you need to make changes, you can jump right to the spot in your script where those changes need to be made, get your work done, and go back to living the high life of a PHP programmer.

But be warned: refactoring isn’t usually the most fun way to spend a Friday night. A lot of the time, the goal in refactoring is to not change how your code works, and especially to not change what it outputs in a browser. Since you’re rearranging—and sometimes optimizing (making things run as smoothly as possible)—your goal is keep things looking the same.

That’s the case with your refactoring of getFormInfo.php. You added some PHP, created a bunch of variables, and then used those variables in your HTML. The result? Exactly the same as your un-refactored version. But now your code’s a lot easier to understand, and you’re actually going to get some nice benefits by having those variables available, as you’ll see on the next page.

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_nameto 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.

UNDER THE HOOD: PROGRAMMING LANGUAGES LIKE ZEROES

The more you program in languages like PHP, or Java, or C, or Perl, the more you’ll see some unusual uses of the number 0. In almost all these languages—and certainly in PHP—counting begins at 0, rather than 1. So if you were counting up the length of the text “That’s weird,” then the first letter—the capital “T”—would be at position 0, not position 1.

This system gets particularly tricky when you’re searching for text within text, like in getFormInfo.php. Suppose someone types facebook.com/michael.greenfield into the Facebook URL text box. Then, in your code, you did something like this to see if the form value was a real URL:

if (strpos($facebook_url,

                  "facebook.com") > 0) {

   $facebook_url =

         "http://www.facebook.com/" .

          $facebook_url;

}

On the face of it, this PHP looks good: if facebook.com doesn’t appear in the first position or greater of $facebook_url, add http://www.facebook.com/ to the front of $facebook_url.

But the result would not be good. You’d actually have a value like this in $facebook_urlhttp://www.facebook.com/facebook.com/michael.greenfield. So what happened?

Well, remember, PHP starts counting at 0, not 1. So position 0 is actually the first position in $facebook_url. And that position has an “f” in it. Position 1 has an “a”, position 2 a “c”, and so on. It turns out that the whole first part of $facebook_url is actually facebook.com, the string for which your code is searching. So strpos() returns a 0 to indicate that the searched-for string is in the first position of $facebook_url.

What this all means—besides the fact that programming languages count differently than real humans—is that you’ve got to be a zero-based thinker when you’re writing code. So if you’re searching for something within a string, a position of 0 or greater means the string was found, rather than 1 or greater. Remember that, and you’ll save yourself a ton of bug hunting.

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=100000039185327was 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.

FREQUENTLY ASKED QUESTION: WHAT’S WITH ALL THE ANGLE BRACKETS?

Any time you’re using PHP to show a lot of HTML, and then dropping little bits of PHP into that HTML, things can get pretty confusing. Take a look at one of the lines you’ve got in getFormInfo.php:

<a href="<?php echo $facebook_url; ?>">

  Your Facebook page

</a><br />

Some of that is strange, to say the least: you’ve got two opening angle brackets at the beginning, and then two at the end. On top of that, you’ve got all the PHP within quotation marks.

Unfortunately, this strangeness is one of the downsides to inserting PHP into HTML. It’s a necessary evil, and it’s something you’ll get used to, but it can still trip you up. Anytime you have PHP code, you really should surround it in <?php and ?>. (You don’t have to, though; you can leave off ?> if you’re ending your script with PHP, but that’s generally considered a lazy practice.) And if you’re using PHP to insert something into an element that’s already in brackets, you’ll get this strange double-bracketed code.

It’s also common to use PHP to generate a link, which in the case of an a element, becomes the value of an attribute. That means your entire PHP block will be surrounded by quotation marks.

That’s okay—as long as your PHP doesn’t also have quotation marks. If you do have a case where you need quotation marks within your PHP, and that PHP is already within quotes, you can alternate single- and double-quote marks, like this:

<a href="<?php echo

         'http://www.twitter.com/' .

          $twitter_handle; ?>">

  Your Facebook page

</a><br />

You can flip these around without a problem, too:

<a href='<?php echo

          "http://www.twitter.com/" .

           $twitter_handle; ?>'>

  Your Facebook page

</a><br />

Just be sure you don’t open something with single quotes, and close it with double quotes, or vice versa. That will cause things to break, and nobody wants that.

There actually are some differences in how PHP handles double-quoted strings and single-quoted strings, but it’s nothing you need to worry about right now.

$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:

§  Users enter extra spaces around words, like “ http://www.facebook.com/ryan.geyer ” instead of “http://www.facebook.com/ryan.geyer”.

§  Users mix up .com and .org URLs, by putting in something like “http://www.facebook.org/profile.php?id=534643138” instead of “http://www.facebook.com/profile.php?id=534643138”.

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.

POWER USERS’ CLINIC: CHAIN YOUR METHODS (OR NOT!)

You may have noticed that lots of times, what you can do in several separate steps, PHP lets you do in a single step. So look at this line in your PHP script:

$facebook_url =

  str_replace(

    "facebook.org",

    "facebook.com",

    trim($_REQUEST['facebook_url']));

This code actually combines several different things. You could rewrite this code like the following, to make all those separate things a little clearer:

$facebook_url = $_REQUEST['facebook_url'];

$facebook_url = trim($facebook_url);

$facebook_url =

  str_replace(

    "facebook.org", "facebook.com",

    $facebook_url);

Both of these code examples work the same, and from a performance and technical point of view, one isn’t any better than the other. That means it’s up to you which version you prefer. So how do you decide?

There are two basic schools of thought here. The first is common in programmer circles, and it’s the “brevity is the soul of wit” approach to programming: “Why do in two, or three, or four lines, what you can get done in one line?” So with this approach, anytime you can combine steps, you should. The code is a lot shorter, and you don’t have a lot of those in-between steps. The result is what’s called method chaining: you do one thing to a piece of text, for example, and then the result of that one thing is sent to another thing. In other words, each step is a link in a chain, and the entire line is the chain, complete and ready to use.

The other school of thought is a little less popular among programmers, unless those programmers have to teach what they’re doing to someone else. Above all else, this school of thought aims to make code easy to understand. So the more you can break down that chain of actions, the easier it is to quickly figure out what’s going on. This takes a lot more code, but all that extra code is easier to understand, and (at least in theory) to fix if something goes wrong.

Realistically, you’ll probably want to end up somewhere in the middle of these two approaches. For instance, your code in getFormInfo.php is still pretty clear, even though a few things are chained together. But if you end up lines that have 6, 7, even 10 things attached to each other, it might be time to split things up (and lay off the triple ventis from Starbucks!).

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.

TAKE IT FURTHER: PHP OFFERS A SLEW OF STRING FUNCTIONS

Believe it or not, you’ve really just scratched the surface of what PHP has to offer in dealing with strings and text. You can visit www.php.net/manual/en/ref.strings.php to get a complete list of what you can do with text in PHP. But get your high-resolution monitor out; this list won’t even fit on a single screen for most web browsers.

But don’t worry—you in no way have to memorize all these functions. Just bookmark this page—and the PHP manual, at www.php.net/manual—and know that it’s there when you need it. If you run across a string you need to manipulate, just pull up your bookmarked PHP manual and search through it. That’s what everybody else does. (Well, there may be some Dustin Hoffman lookalike out there rattling off all the PHP numerical functions in a monotone, all Rain-Manned up in his gray suit. But that guy is the exception.)

Instead of worrying about memorizing the odds and ends of every function in the PHP language, work on understanding the patterns of PHP, and how those patterns work. For instance, now you know that most string manipulation involves calling some function, passing it in a few pieces of information, and assigning the result to a variable. That’s what’s important, and now every time you do look up a string function in the PHP manual, you know exactly how to use that function correctly.

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] = "derek@DerekTrucks.com";

$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] = "derek@DerekTrucks.com";

$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 "\nEmail: " . $email;

echo "\nFacebook URL: " . $facebook_url;

echo "\nTwitter 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'] = "derek@DerekTrucks.com";

$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 "\nEmail: " . $email;

echo "\nFacebook URL: " . $facebook_url;

echo "\nTwitter 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.