PHP is a powerful scripting language that fits gracefully into HTML and puts the tools for creating dynamic websites in the hands of the people — even people like me who were too lazy to learn Perl scripting and other complicated backend hoodoo.
This tutorial is for the person who understands HTML but doesn’t know much about PHP. One of PHP’s greatest attributes is that it’s a freely distributed open-source language, so there’s all kinds of excellent reference material about it out there, which means that once you understand the basics, it’s easy to find the materials that you need to push your skills.
PHP is a program that gets installed on top of your web server software. It works with versions of Apache (Tutorial:Apache for Beginners), Microsoft IIS and other server software packages.
You use PHP by inserting PHP code inside the HTML that makes up your website. When a client (anybody on the web) visits a web page that contains this code, your server executes it. That’s why you need to install your own server in order to test PHP locally — the server is the brain here, not your browser. Users don’t need any special plug-ins or anything to see your PHP in action — it gets to the end user as regular old-fashioned HTML.
PHP is a scripting language, like HTML. That means that code does not need to be compiled before it gets used — it gets processed on the fly as necessary.
Before we dig in, you should know about a site called PHP.net. PHP is an open-source language, and PHP.net is its control center, with extensive reference material about the language and tips sent in by users across the globe. PHP.net has exceptional, deep information about the language, but it can be a little cryptic for the newcomer. We’ll look more closely at how to use PHP.net at the end of this tutorial.
So, what kinds of things can PHP do? Welllll … it can:
The ?php and ?¢ tags start and end a PHP script, and your meat goes in the middle. Got that? Good! Now let’s walk through the basic rules you need to know to before you can write your first PHP script.
If you have space on a web server which supports PHP, you can also test your PHP there, but this is kind of a pain because it means you’ll need to FTP your files or telnet in every time you want to change something.
See how that works? The HTML is rendered as regular HTML, but everything inside the ?php and ?¢ tags gets processed as PHP.
Naming Files In order to get a PHP script working, the file it’s in or the file that it calls to do the heavy lifting must end in .php (earlier versions used the file extensions .php3 and .phtml). Like HTML, your files are saved as plain text.
Comments It’s important to get in the habit of leaving notes about your code with the comment tags so that months down the road you can make sense of what you were trying to make your script do. The way you set comments apart from your code (that you don’t want displayed or executed) is with either “//” at the beginning of each line, or surrounded by “/*” and “*/” if you want to comment out several lines:
Every Chunk With a few exceptions, each separate instruction that you write will end with a semicolon.
Parentheses The typical function looks like this …
… where “print” is the function and the stuff that the function works on sits inside the parentheses, with a semicolon to finish it off. (Just to confuse you, “print” is the exception that also works without parentheses.) By the way, echo () is the same as print ().
Much like HTML, the actual formatting of your PHP code (where you put spaces, line breaks, etc.) will not affect the outcome except those parts of the code that tell a web browser how to display your page. So this piece of code …
Like more complicated HTML, it behooves you to use white space and tabs in your code to make the code more understandable.
Ready to write your first script? Let’s go.
Save the file with any name that has no spaces and ends in .php, and if you’ve installed a server on your own machine, you need to save the script somewhere inside the server’s root folder (on Windows this is typically in the “wwwroot” directory inside the “inetpub” directory on your C: drive).
The next step is to open the file in your browser. Since you need the server to run your PHP code, you have to open the file through a URL that finds the correct file through your web server. On Windows, your computer name is your root URL. My computer name is “rocketboy,” so to see the contents of my root directory, I type “http://rocketboy” into the Web browser and voila! I see the contents of my root folder. To open the file “chickenman.php” in a directory called “tests” inside the root directory, I’d type “http://rocketboy/tests/chickenman.php” and see my example.
If you’re testing on a PHP-able web server, FTP your files anywhere on your server and they should work when you open them through the URL.
Go on now and get your first script working. Then come back and we’ll have some fun. Together. (If you can’t get your first script working, look at our First Script Troubleshooting Guide.)
Error messages can be very useful and you’re bound to run into lots of them. You’ll get a message like this for every line in your script that has an error. For our purposes, all we really need to know is that there is something wrong with our code in line 12 of the document “test9.php,” so let’s look at that line and see if we can figure it out (good text editors like BBEdit have a function that lets you jump to any particular line). I always start by looking to see if my basic syntax is correct: did I leave out the closing tag, a line’s semicolon, quotation marks?
In the same code that you wrote before, drop in a couple more statements. As you see, you can gang up more than one PHP function inside the same opening and closing tags. My comments in the code explain what each part does:
NOTE: Phpinfo will output a long page of info about your version of PHP. You don’t need to understand what it all means, I just wanted to show you that it’s there if you ever need it.
The reason why variables are so important to PHP is that the very notion of having dynamic web pages — pages which respond somehow to user input — relies on data being passed around between pages (or parts of a page). Variables are the main mechanism for transferring data like this.
I think the easiest way to explain how variables work in PHP is to show them in action. There are three basic things you can do with variables:
Here’s what that page will look like:
In line two I have created a variable that I decided to name “utterance.” All variables start with “$”, so my variable is written “$utterance” in the code. Here’s how that last code snippet breaks down line by line. Please note: the webserver does the PHP interpreting before sending the browser finished HTML code.
The syntax of setting a variable is to:
In the examples so far, we have set variables as chunks of text, which are known as “strings.” Variables can also hold the values of numbers and some other things as well (objects, arrays, booleans).
Final note: One thing that can be a little confusing when starting to use PHP is the use of quotation marks inside PHP functions. Use single or double quotes to set off strings (that is, chunks of text), as in:
This will print the text I am the CHICKEN MAN. If you want to display quotation marks as characters in the output of your PHP script, you must escape them with the “” character, which tells PHP not to use the next character as part of the code. So to output the text “I am the CHICKEN MAN” (with quotation marks showing in the result) the code would look like:
Let’s get some real mileage by creating HTML forms to gather user input, turning that input into variables, and then doing various things with the information that we just collected.
No sense in sitting around waiting – let’s go ahead and make a Web page that collects your favorite dirty word and displays it on another page that tells you what a pervert you are. All of this gives a page that looks a lot like this.
First, we make the form page, which is regular HTML with a form in it. I’m calling mine “badwords_form.html,” but call yours whatever you like. (If you want a good primer on HTML forms, read Jay’s How To Add HTML Forms to Your Sitetutorial.)
This is a regular HTML form. The important pieces are as follows:
Line 7: the HTML that reads action="bad_words.php" tells the browser which PHP document will process the results of the form. That is to say, in a minute you’ll create a document called “bad_words.php” which will be the little engine that makes the result page happen. (We’ll get to the method=post part later on.)
Line 10: input type="text" determines that the form element which we want here is “text” or a text box (we could also have a radio button, check box, etc.); name="YourName" determines that whatever the user types into the text box will become a variable that we have called “YourName.” This is what ties together forms and variables – each form field can set a variable to be used however you want.
Line 13: here you have another text input that sets a variable called “FavoriteWord” which is the user’s favorite dirty word.
Line 16, 17: This code makes a submit button with the text “That’s Right!” and ends the form.
So this form will collect the unassuming user’s name and favorite bad word, but now what do we do with it? Let’s take the variables she set and echo them back in another context on another page.
On line 7 of the HTML above, we told the form to head on over to bad_words.php once the submit button was hit. This is what bad_words.php looks like:
See how this form passed a variable along from the form page to the PHP file? You have not seen the last of this.
The difference between these two is that the “post” method transparently passes along all the information the page has gathered, whereas the “get” method will pass all that info along as part of the URL (in the form above, this would look like: http://rocketboy/webmonkey_article/bad_words.php?YourName=bob&FavoriteWord=crikey%21&submit=Enter+My+Data%21 – see how the info the user entered about his name and his favorite word get added to the URL?)
Arrays give you the ability to store not just one value inside a variable, but a whole bunch of values in a single variable.
If I wanted to catalog all of the animals in my house, I could set each one as a regular variable. I’ve got two dogs, Phoebe and Ruby, and a squirrel that died in the attic last year, whom we’ll call Rotty. Setting each one as a variable looks like this:
But an array will let us store all these inside one single variable, which I’ll call $critters. Each element of the variable has its own “key” that is used to access that part of the array, which can either be a string of letters or numbers.
Let me explain the “key” concept another way: If we’re storing three different values inside one variable (like storing Phoebe, Ruby, and Rotty inside $critters), we need some way to be able to suck out any individual part of the array to use it. An array will automatically number each element that comprises it, so the key can be element 1, element 2, and element 3. Or, as we’ll see later on, we can name each part of the array with text. In this case I could make the keys “fat dog,” “skinny dog,” and “squirrel” and use those to identify each array member.
Let’s make a simple array and then use it. The easiest way to create an array is to use the array() function, which assigns a bunch of values to your array at once and looks like this:
This stores all my animal names into one variable ($critters) in an array, and automatically assigns a numbered “key” to each element starting in order and giving the first element the number 0. So Phoebe is element [0], Ruby is [1], Rotty is [2], etc. I make up the name of the array myself (here it’s $critters).
You can now get at any of the array elements by referring to the variable followed by the element number in square brackets: $critters[0], for example. Here it is in action:
This will simply print the third element in the array, which is Rotty (don’t forget that array numbers start at 0, so $critters[2] is third after $critters[0] and $critters[1]).
There’s another way to set an array, or even to add to an existing array, by setting each element individually:
This’ll have the same effect as using the array() function, giving the first element the key [0] and so on. But wait! I forgot about Opie the cat. Hmmm. Regardless of how we made the array in the first place, I can easily add Opie like this:
PHP is smart enough to count the number of elements and give Opie the next available one, which in this case (after Phoebe, Ruby, and Rotty) is [3].
To recap this concept, I can set an array to include the animals in my house either this way:
Or this way:
Both will be indexed in the computer brain with the values:
And in both cases, you could get at any element in the array by describing its number …
… which would print the string Opie to the window of your browser.
Arrays can be made to do all kinds of things, like being incremented by number, sorted in alphabetical order, printed by different types of categorization, and many more.
Here we’re telling the array to create the keys “name,” “description,” “color,” and “age”; and we give each of those keys a value (name is “Phoebe”, description is “fat dog,” and so on).
We can get at any part of the array through the “key” names that we set, for example:
will give us grey and white. We can also set each key individually, like so:
Finally, let’s make it hurt. We’re going to get some serious power out of this arrays business by creating a “multi-dimensional” array. A multi-dimensional array is an array (say the animals in my house) that is made up of other arrays (for each animal, an array that contains the critter’s name, color, description, and age).
We make multi-dimensional arrays by creating one array:
…and then we fill that array with an array of animals in which we’ve defined the keys, like this:
To use this now, we can get any part of the information contained in there by naming the overall array ($animals), naming the number of the sub-array that we want to find out about (Phoebe is [0], Ruby is [1], etc.) and then naming the key for the attribute we want to get at (name, type, color, or age).
To find out the age of the cat, we’d write:
Here’s what it all looks like together. This is all in one page, but remember that you can set arrays in one place (in code or in form fields from another page or in a database, say) and get at the info contained within from somewhere else. Here I’m putting it all together on one page so you can see it all at once.
What we’ve just done is create an array that includes a sub-array for each animal which contains detailed info about that critter; then we print a sentence that uses the type and ages of two of the animals.
statement, which gives you the ability to code:
The syntax of this statement is as follows:
Here it is in action. First we set the variable
Please note that:
and
are not the same thing, the first will always be true as it sets $FavoriteColor to blue.
It works like this:
Here it is in motion:
What you see above is the typical format for writing statements like this. The key part is to see where the curly braces are so you don’t get confused as to which statement belongs to which piece of the code. Above, the first set of { and } belong to the “if,” the second { and } belong to the “else.”
It looks like this:
You could even add an ELSE statement at the end in case FavoriteColor were neither blue nor green.
But you can squeeze a lot more juice out of your PHP using what are called “comparison operators,” “logical operators,” and “arithmetic operators.” Here’s what they are, in tables copied verbatim from PHP.net.
The while loop says,
While loops are often used with incrementing and decrementing a variable that is an integer. What in the hell does that mean? It means that you can automatically have the script add (or subtract) a whole number (1, 2, 3, etc.) from part of a script each time it runs through, until the number reaches a maximum or minimum value that you’ve set.
So if you wanted a script to print the numbers from 1 to 10, you can tell it (this is English, not PHP here):
The syntax for incrementing and decrementing the value of a variable is:
So the code itself for printing the numbers 1 through 10 could look like this:
PHP, however, is very flexible. Not only does PHP have a library of canned functions that’ll do everything from sorting stuff in alphabetical order to sending email, from connecting with databases to balancing your spaceship’s inertial sub-space dampers, but you can also create your very own functions to do all manner of things related to your website. The functions you create get executed exactly like those from the PHP library, but they’re your own. In the following section, I’ll show a glimpse of how you create your own functions and feel the power.
Functions you create are like little machines that do something for you. You construct them and then call them as needed.
You’ll remember that the very first thing we learned to do was a simple “print” statement, which followed the form:
Functions that you create are built upon a similar form, but take it farther:
So you start a function with the words function WhatYouNameIt(), with the words WhatYouNameIt() being anything you choose (no spaces).
Then you define the rules of the function inside the following curly brackets (that’s { and } on lines 5 and 9). Don’t you just love the words “curly brackets?”
Let’s walk through the making of a couple functions. Functions come in two flavors, those that require “arguments” and those that don’t. An “argument” is a variable that comes from outside the function, but which the function needs in order to run.
Let’s first look at one that doesn’t require arguments:
line 1: start PHP;
line 3: create function ChickenMan;
line 5: start definition of function ChickenMan;
line 7: definition of ChickenMan is to print “I am the CHICKEN MAN!” inside and tags;
line 9: end definition of ChickenMan;
line 11: call function ChickenMan (meaning “do the thing that we defined the function to do”);
line 13: close PHP;
Any place in this web page that you put “ChickenMan();” inside the tags, it’ll print your little statement. See how this saves you time if you want to print this string a bunch of times in different places?
Now let’s get a little more complicated and create a function that does take arguments. Say I’m a loan shark and I’m going to loan you the money to buy that personal hovercraft you’ve been lusting after. I’ll lend you however much you need, but you have to pay me 14 percent interest per week or I break your legs.
I’ll create a function called InterestPayment which calculates your weekly payments (until you pay off the whole loan amount in one lump sum).
First we’ll create a form page where the user enters how much of a loan he or she wants. The user enters the hovercraft’s sticker price, and that number gets passed along from the form as a variable called font size="2">$Cost. (For the HTML behind this, go here.)
Next, our function will take the amount that the user enters into the variable font size="2">$Cost and spit back 14 percent of that amount, which is how much the hapless borrower owes every week. This will happen in the PHP page titled “loanshark.php” that the form page points to (it points with this code:
This tutorial is for the person who understands HTML but doesn’t know much about PHP. One of PHP’s greatest attributes is that it’s a freely distributed open-source language, so there’s all kinds of excellent reference material about it out there, which means that once you understand the basics, it’s easy to find the materials that you need to push your skills.
Contents |
Introduction
What Is PHP?
So, what is this whole PHP business all about?PHP is a program that gets installed on top of your web server software. It works with versions of Apache (Tutorial:Apache for Beginners), Microsoft IIS and other server software packages.
You use PHP by inserting PHP code inside the HTML that makes up your website. When a client (anybody on the web) visits a web page that contains this code, your server executes it. That’s why you need to install your own server in order to test PHP locally — the server is the brain here, not your browser. Users don’t need any special plug-ins or anything to see your PHP in action — it gets to the end user as regular old-fashioned HTML.
PHP is a scripting language, like HTML. That means that code does not need to be compiled before it gets used — it gets processed on the fly as necessary.
Before we dig in, you should know about a site called PHP.net. PHP is an open-source language, and PHP.net is its control center, with extensive reference material about the language and tips sent in by users across the globe. PHP.net has exceptional, deep information about the language, but it can be a little cryptic for the newcomer. We’ll look more closely at how to use PHP.net at the end of this tutorial.
So, what kinds of things can PHP do? Welllll … it can:
- take info from web-based forms and use it in a million ways (store it in a database, create conditional pages depending on what the forms said, set cookies for later, send e-mail, write your mom on her birthday);
- authenticate and track users;
- run threaded discussions on your site;
- serve different pages to people using different browsers or devices;
- publish an entire website using just a single layout template (server-side includes-style);
- serve XML pages.
1 |
|
2 |
3 |
4 |
5 | print ( "I am the CHICKEN MAN" ); |
6 |
7 |
8 |
9 | ?> |
What you’ll need
Before we begin, you will need to install a server on your own machine in order to test your PHP scripts locally. You can install WampServer for Windows machines from http://www.wampserver.com/en/ In order to have a Localhost machine. If you’re using a Mac you can get MAMP from http://www.mamp.info.If you have space on a web server which supports PHP, you can also test your PHP there, but this is kind of a pain because it means you’ll need to FTP your files or telnet in every time you want to change something.
Steps
The Basics
The code itself fits right inside a page’s HTML, and like HTML it is made up of plain ol’ text. So a page that displays the words “I am the CHICKEN MAN!” message would sit inside an HTML page named something.php, like this:01 |
|
02 |
03 |
|
04 |
05 |
06 |
|
07 |
08 |
09 | print ( "I am the CHICKEN MAN" ); |
10 | ?> |
11 |
12 |
13 |
Basic Syntax
It’s time to write your own first PHP script. The basic rules of PHP are as follows:Naming Files In order to get a PHP script working, the file it’s in or the file that it calls to do the heavy lifting must end in .php (earlier versions used the file extensions .php3 and .phtml). Like HTML, your files are saved as plain text.
Comments It’s important to get in the habit of leaving notes about your code with the comment tags so that months down the road you can make sense of what you were trying to make your script do. The way you set comments apart from your code (that you don’t want displayed or executed) is with either “//” at the beginning of each line, or surrounded by “/*” and “*/” if you want to comment out several lines:
01 |
|
02 |
03 | // This will be ignored. Note to self: |
04 |
05 | // Pick up ice cream, cake, and balloons. |
06 |
07 | print ( "I am the CHICKEN MAN" ); |
08 |
09 | /* |
10 |
11 | This, too, will be ignored. |
12 |
13 | Hey, and don't forget |
14 |
15 | the spanking machine! |
16 |
17 | */ |
18 |
19 | ?> |
Code Syntax
Start of Code Every piece of PHP code begins with “ End of Code The way to signify that the PHP code is finished is by adding “?>” at the end.Every Chunk With a few exceptions, each separate instruction that you write will end with a semicolon.
Parentheses The typical function looks like this …
1 | print ( ); |
Much like HTML, the actual formatting of your PHP code (where you put spaces, line breaks, etc.) will not affect the outcome except those parts of the code that tell a web browser how to display your page. So this piece of code …
01 |
|
02 |
03 |
04 |
05 | print ( "I am the CHICKEN MAN" ); |
06 |
07 |
08 |
09 | ?> |
10 |
11 |
12 |
13 | ... is effectively identical to: |
14 |
15 |
16 |
17 |
|
Ready to write your first script? Let’s go.
Your First Script
OK, so write your first script already! Copy the following script, but put whatever you want inside the quotation marks. “Print” here means print to the screen of a web browser when you open the file:01 |
|
02 |
03 |
|
04 |
05 |
|
06 |
07 | print ( "I am the CHICKEN MAN" ); |
08 |
09 | ?> |
10 |
11 |
|
12 |
13 |
|
The next step is to open the file in your browser. Since you need the server to run your PHP code, you have to open the file through a URL that finds the correct file through your web server. On Windows, your computer name is your root URL. My computer name is “rocketboy,” so to see the contents of my root directory, I type “http://rocketboy” into the Web browser and voila! I see the contents of my root folder. To open the file “chickenman.php” in a directory called “tests” inside the root directory, I’d type “http://rocketboy/tests/chickenman.php” and see my example.
If you’re testing on a PHP-able web server, FTP your files anywhere on your server and they should work when you open them through the URL.
Go on now and get your first script working. Then come back and we’ll have some fun. Together. (If you can’t get your first script working, look at our First Script Troubleshooting Guide.)
Error Messages
Fun, eh? Fun if it worked. If not — if you had an error in your script — you probably got an error message that looked something like this:1 | Parse error: |
2 |
3 | parse error in C:Inetpubwwwrootwebmonkey_articletest9.php |
4 |
5 | on line 12 |
A Few More Statements
Let’s continue by adding to your test code from the last page to show a couple useful tools.In the same code that you wrote before, drop in a couple more statements. As you see, you can gang up more than one PHP function inside the same opening and closing tags. My comments in the code explain what each part does:
01 |
|
02 |
03 |
04 |
05 | This text right here (or any HTML I want to write) |
06 |
07 | will show up just before the PHP code stuff. |
08 |
09 |
10 |
11 |
12 |
13 | // first, this $PHP_SELF thang is |
14 |
15 | // an environment variable that'll show the |
16 |
17 | // path from your root folder to this |
18 |
19 | // document itself, like /webmonkey_article/test3.php. |
20 |
21 | // I put this in just for fun. |
22 |
23 | // NOTE: This may only work if your server is Apache. |
24 |
25 | print "$PHP_SELF" ; |
26 |
27 | // next we have to "print" any |
28 |
29 | // HTML code we want the browser |
30 |
31 | // to follow to determine |
32 |
33 | // the layout of the results page. |
34 |
35 | // In this case, we're adding a tag |
36 |
37 | // the tags could have been put |
38 |
39 | // inside the same print statement as the |
40 |
41 | // "I am the CHICKEN MAN" text. |
42 |
43 | // between the $PHP_SELF text and the |
44 |
45 | // next bunch of stuff. |
46 |
47 | print ( " " ); |
48 |
49 | print ( "I am the CHICKEN MAN" ); |
50 |
51 | print ( " " ); |
52 |
53 | /* This next "phpinfo" business outputs a long page that |
54 |
55 | tells you exactly how your version of PHP is configured. |
56 |
57 | This can be useful when troubleshooting problems down |
58 |
59 | the road */ |
60 |
61 | phpinfo(); |
62 |
63 | ?> |
64 |
65 |
66 |
67 |
68 |
69 |
Very Able Variables
So far, all we’ve done is have a PHP script print some text. Big whoop. Let’s get down and dirty now with variables. A variable is a container for holding one or more values. It is the means by which PHP stores information and passes it along between documents and functions and such. You may remember variables from algebra — in the equation “x + 2 = 8″, x is a variable with the value 6.The reason why variables are so important to PHP is that the very notion of having dynamic web pages — pages which respond somehow to user input — relies on data being passed around between pages (or parts of a page). Variables are the main mechanism for transferring data like this.
I think the easiest way to explain how variables work in PHP is to show them in action. There are three basic things you can do with variables:
- Set them (give them one or more values);
- Re-set them if they were set before;
- Access them (read the value of a variable and then do something useful with it).
01 | 1. |
02 |
03 | 2. $utterance = "I love you!" ; |
04 |
05 | 3. print ( "When I'm happy, I want to say $utterance" ); |
06 |
07 | 4. print ( " " ); |
08 |
09 | 5. $utterance = "I will smite you!" ; |
10 |
11 | 6. print ( "When I'm angry, I want to say $utterance" ); |
12 |
13 | 7. ?> |
In line two I have created a variable that I decided to name “utterance.” All variables start with “$”, so my variable is written “$utterance” in the code. Here’s how that last code snippet breaks down line by line. Please note: the webserver does the PHP interpreting before sending the browser finished HTML code.
- Line 1 tells the webserver: “Start PHP code here”.
- Line 2 creates the variable $utterance and also sets it, giving it the initial value of “I love you!”.
- Line 3 prints a phrase that draws on the variable $utterance.
- Line 4 creates a tag in HTML to put vertical space between the two utterances.
- Line 5 RE-SETS the variable $utterance and gives it the value “I will smite you!”.
- Line 6 prints a new phrase that draws on the new meaning of the variable $utterance.
- Line 7 tells Mr. Webserver: PHP code ends here.
The syntax of setting a variable is to:
- define it with the = sign ($utterance = “I love you!”;);
- use quotation marks if you’re defining it with a string of letters (“I love you!”; numbers don’t require quotes);
- end each instruction with a semicolon.
Naming Variables
You can name a variable anything you want so long as it follows these rules:- it starts with a letter;
- it is made up of letters, numbers, and the underscore character (that’s the _ character, as in “$baby_names”);
- it isn’t used elsewhere (like “print”).
In the examples so far, we have set variables as chunks of text, which are known as “strings.” Variables can also hold the values of numbers and some other things as well (objects, arrays, booleans).
Final note: One thing that can be a little confusing when starting to use PHP is the use of quotation marks inside PHP functions. Use single or double quotes to set off strings (that is, chunks of text), as in:
1 | print ( "I am the CHICKEN MAN" ); |
1 | print ( " " I am the CHICKEN MAN "" ); |
HTML Forms and PHP
In our examples so far, we have set variables and then used them all in the same code. This doesn’t make much sense because in those instances, we could have just hard-coded the values instead of using variables.Let’s get some real mileage by creating HTML forms to gather user input, turning that input into variables, and then doing various things with the information that we just collected.
No sense in sitting around waiting – let’s go ahead and make a Web page that collects your favorite dirty word and displays it on another page that tells you what a pervert you are. All of this gives a page that looks a lot like this.
First, we make the form page, which is regular HTML with a form in it. I’m calling mine “badwords_form.html,” but call yours whatever you like. (If you want a good primer on HTML forms, read Jay’s How To Add HTML Forms to Your Sitetutorial.)
01 |
|
02 |
03 |
04 |
05 |
|
06 |
07 |
08 |
09 |
10 |
11 |
12 |
13 | My name is: |
14 |
15 |
|
16 |
17 | My favorite dirty word is: |
18 |
19 |
|
20 |
21 |
|
22 |
23 |
24 |
25 |
26 |
27 |
Line 7: the HTML that reads action="bad_words.php" tells the browser which PHP document will process the results of the form. That is to say, in a minute you’ll create a document called “bad_words.php” which will be the little engine that makes the result page happen. (We’ll get to the method=post part later on.)
Line 10: input type="text" determines that the form element which we want here is “text” or a text box (we could also have a radio button, check box, etc.); name="YourName" determines that whatever the user types into the text box will become a variable that we have called “YourName.” This is what ties together forms and variables – each form field can set a variable to be used however you want.
Line 13: here you have another text input that sets a variable called “FavoriteWord” which is the user’s favorite dirty word.
Line 16, 17: This code makes a submit button with the text “That’s Right!” and ends the form.
So this form will collect the unassuming user’s name and favorite bad word, but now what do we do with it? Let’s take the variables she set and echo them back in another context on another page.
On line 7 of the HTML above, we told the form to head on over to bad_words.php once the submit button was hit. This is what bad_words.php looks like:
|
|
Get versus Post
So far, we’ve used the “Post” method of passing form data as opposed to the other method, “Get.” This is the part of the form code that reads form action="bad_words.php" method=post¢.The difference between these two is that the “post” method transparently passes along all the information the page has gathered, whereas the “get” method will pass all that info along as part of the URL (in the form above, this would look like: http://rocketboy/webmonkey_article/bad_words.php?YourName=bob&FavoriteWord=crikey%21&submit=Enter+My+Data%21 – see how the info the user entered about his name and his favorite word get added to the URL?)
Arrays
One of your best tools now that you’ve mastered variables – you have, haven’t you? – are arrays.Arrays give you the ability to store not just one value inside a variable, but a whole bunch of values in a single variable.
If I wanted to catalog all of the animals in my house, I could set each one as a regular variable. I’ve got two dogs, Phoebe and Ruby, and a squirrel that died in the attic last year, whom we’ll call Rotty. Setting each one as a variable looks like this:
1 | $dog1 = "Phoebe" ; |
2 |
3 | $dog2 = "Ruby" ; |
4 |
5 | $squirrel1 = "Rotty" ; |
Let me explain the “key” concept another way: If we’re storing three different values inside one variable (like storing Phoebe, Ruby, and Rotty inside $critters), we need some way to be able to suck out any individual part of the array to use it. An array will automatically number each element that comprises it, so the key can be element 1, element 2, and element 3. Or, as we’ll see later on, we can name each part of the array with text. In this case I could make the keys “fat dog,” “skinny dog,” and “squirrel” and use those to identify each array member.
Let’s make a simple array and then use it. The easiest way to create an array is to use the array() function, which assigns a bunch of values to your array at once and looks like this:
1 | $critters = array ( "Phoebe" , "Ruby" , "Rotty" ); |
You can now get at any of the array elements by referring to the variable followed by the element number in square brackets: $critters[0], for example. Here it is in action:
1 |
|
2 |
3 |
4 |
5 | print "$critters[2]" ; |
6 |
7 |
8 |
9 | ?> |
There’s another way to set an array, or even to add to an existing array, by setting each element individually:
1 | $critters[] = "Phoebe" ; |
2 |
3 | $critters[] = "Ruby" ; |
4 |
5 | $critters[] = "Rotty" ; |
1 | $critters[] = "Opie" ; |
To recap this concept, I can set an array to include the animals in my house either this way:
1 | $critters[] = "Phoebe" ; |
2 |
3 | $critters[] = "Ruby" ; |
4 |
5 | $critters[] = "Rotty" ; |
6 |
7 | $critters[] = "Opie" ; |
1 | $critters = array ( "Phoebe" , "Ruby" , "Rotty" , "Opie" ); |
1 | $critters[0] = "Phoebe" ; |
2 |
3 | $critters[1] = "Ruby" ; |
4 |
5 | $critters[2] = "Rotty" ; |
6 |
7 | $critters[3] = "Opie" ; |
1 |
|
2 |
3 |
4 |
5 | print "$critters[3]" ; |
6 |
7 |
8 |
9 | ?> |
Arrays can be made to do all kinds of things, like being incremented by number, sorted in alphabetical order, printed by different types of categorization, and many more.
Associative Arrays
Ready to get more complicated? The associative array indexes the contained elements not by numbers, but by names that you determine. Inside the array() function, you set up pairs where you name the key and its value using the combo of the “=” and the “>”, like: key=>”value”. Here’s what it looks like in action:01 | $PhoebeDog = array ( |
02 |
03 | name=> "Phoebe" , |
04 |
05 | description=> "fat dog" , |
06 |
07 | color=> "grey and white" , |
08 |
09 | age=>7 |
10 |
11 | ); |
We can get at any part of the array through the “key” names that we set, for example:
1 | print $PhoebeDog[color]; |
1 | $animals[name] = "Phoebe" ; |
2 |
3 | $animals[description] = "fat dog" ; |
4 |
5 | $animals[color] = "grey and white" ; |
6 |
7 | $animals[age] = 7; |
We make multi-dimensional arrays by creating one array:
1 | $animals = array |
2 |
3 | ( |
4 |
5 | ); |
01 | $animals = array ( |
02 |
03 | array ( name=> "Phoebe" , |
04 |
05 | type=> "dog" , |
06 |
07 | color=> "grey and white" , |
08 |
09 | age=>7 ), |
10 |
11 | array ( name=> "Ruby" , |
12 |
13 | type=> "dog" , |
14 |
15 | color=> "brown and white" , |
16 |
17 | age=>7 ), |
18 |
19 | array ( name=> "Rotty" , |
20 |
21 | type=> "squirrel" , |
22 |
23 | color=> "grey" , |
24 |
25 | age=>2 ), |
26 |
27 | array ( name=> "Opie" , |
28 |
29 | type=> "cat" , |
30 |
31 | color=> "grey tabby" , |
32 |
33 | age=>5 ) |
34 |
35 | ); |
To find out the age of the cat, we’d write:
1 | print $animals[3][age]; |
01 |
|
02 |
03 |
|
04 |
05 |
|
06 |
07 |
|
08 |
09 |
10 |
11 |
|
12 |
13 |
14 |
15 |
|
16 |
17 |
18 |
19 | $animals = array ( |
20 |
21 | array ( name => "Phoebe" , |
22 |
23 | type => "dog" , |
24 |
25 | color => "grey and white" , |
26 |
27 | age => 7 ), |
28 |
29 | array ( name => "Ruby" , |
30 |
31 | type => "dog" , |
32 |
33 | color => "brown and white" , |
34 |
35 | age =>7 ), |
36 |
37 | array ( name => "Rotty" , |
38 |
39 | type => "squirrel" , |
40 |
41 | color => "grey" , |
42 |
43 | age =>2 ), |
44 |
45 | array ( name => "Opie" , |
46 |
47 | type => "cat" , |
48 |
49 | color => "grey tabby" , |
50 |
51 | age => 5 ) |
52 |
53 | ); |
54 |
55 |
56 |
57 | print $animals[2][ "type" ]; |
58 |
59 | print ( " ); |
60 |
61 | print $animals[3][ "color" ]; |
62 |
63 |
64 |
65 | ?> |
66 |
67 |
68 |
69 |
70 |
71 |
|
Operators; If, Else, Elseif; Loops
The whole deal about making dynamic websites is that you want your web page to be as smart as possible — to have code sitting there that can make all sorts of decisions based on different kinds of user input, user conditions (what browser is Visitor X using?), or information that you set yourself. Examples of this could be:- After a user enters an email address, check that it has a valid form (whoever@wherever.com) and if not, serve a page that says, “hey pal, how about a VALID email address?”
- Serve one set of HTML to .com domains and another to .gov domains (where you try not to use any big words that might confuse ‘em).
- Know whether a customer at your online store is meeting a minimum dollar amount for an online credit card purchase.
- And on and on and on – the possibilities are limitless.
If
The way to make your pages smart is to use If, Else, and Elseif statements along with Comparison and Logical Operators. The most important one of these is the1 |
1 | If some condition is true , then do somesuch thing; |
2 |
3 | If the condition is not true , then ignore it; |
1 | if (condition) { |
2 |
3 |
4 |
5 | // code in here to execute if the condition is true |
6 |
7 |
8 |
9 | } |
01 |
|
02 |
03 |
04 |
05 | $FavoriteColor = "blue" ; |
06 |
07 |
08 |
09 | if ($FavoriteColor == "blue" ) { |
10 |
11 |
12 |
13 | print ( "I like blue too!" ); |
14 |
15 |
16 |
17 | } |
18 |
19 |
20 |
21 | ?> |
1 | if ($FavoriteColor = "blue" ) |
1 | if ($FavoriteColor == "blue" ) |
Else
Else builds on the if statement as if to say:1 | If some condition is true , then do somesuch thing; |
2 |
3 | ELSE, in case that first condition is NOT true , then do this other thing. |
01 | if (condition) { |
02 |
03 |
04 |
05 | // code in here to execute if the condition is true |
06 |
07 |
08 |
09 | } else { |
10 |
11 |
12 |
13 | // code in here to execute if the condition is not true |
14 |
15 |
16 |
17 | } |
01 |
|
02 |
03 |
04 |
05 | $FavoriteColor = "yellow" ; |
06 |
07 |
08 |
09 | if ($FavoriteColor == "blue" ) { |
10 |
11 |
12 |
13 | print ( "I like blue too!" ); |
14 |
15 |
16 |
17 | } else { |
18 |
19 |
20 |
21 | print ( "You don't like blue?! Crazy fool!" ); |
22 |
23 |
24 |
25 | } |
26 |
27 |
28 |
29 | ?> |
Elseif
There’s one more sibling in the if, else family, and it’s called elseif. Where else is sort of a blanket control that make something happen as long as the if statement is not true, elseif makes something happen if a specific condition is met:1 | IF some condition is true , then do somesuch thing; |
2 |
3 | ELSEIF some other specific condition is true , then do another thing; |
01 |
|
02 |
03 |
04 |
05 | $FavoriteColor = "green" ; |
06 |
07 |
08 |
09 | if ($FavoriteColor == "blue" ) { |
10 |
11 |
12 |
13 | print ( "I like blue too!" ); |
14 |
15 |
16 |
17 | } elseif ($FavoriteColor = green) { |
18 |
19 |
20 |
21 | print ( "MMMmmmmmmmmmm, green!" ); |
22 |
23 |
24 |
25 | } |
26 |
27 |
28 |
29 | ?> |
Comparison and Logical Operators
We’ve seen how the “=” sign works when we set variables in the scripts we’ve written so far (as in the code$FavoriteColor = "blue"; and $utterance = "I will smite you!"; ). The equal sign here is what we call the “assignment operator” and is the simplest operator we’ve got: $a = b means “the variable a is assigned the value b (for the moment).”But you can squeeze a lot more juice out of your PHP using what are called “comparison operators,” “logical operators,” and “arithmetic operators.” Here’s what they are, in tables copied verbatim from PHP.net.
Comparison Operators
These give you the ability to compare whether elements are equal, identical, less than or greater than one another (with some other variations).Example | Name | Result |
---|---|---|
$a == $b | Equal | TRUE if $a is equal to $b. |
$a === $b | Identical | TRUE if $a is equal to $b, and they are of the same type. (PHP 4 only) |
$a != $b | Not equal | TRUE if $a is not equal to $b. |
$a <> $b | Not equal | TRUE if $a is not equal to $b. |
$a !== $b | Not identical | TRUE if $a is not equal to $b, or they are not of the same type. (PHP 4 only) |
$a < $b | Less than | TRUE if $a is strictly less than $b. |
$a > $b | Greater than | TRUE if $a is strictly greater than $b. |
$a <= $b | Less than or equal to | TRUE if $a is less than or equal to $b. |
$a >= $b | Greater than or equal to | TRUE if $a is greater than or equal to $b. |
Logical Operators
Here you can compare elements using comparisons and, or, and the like.Example | Name | Result |
---|---|---|
$a and $b | And | TRUE if both $a and $b are TRUE. |
$a or $b | Or | TRUE if either $a or $b is TRUE. |
$a xor $b | Xor | TRUE if either $a or $b is TRUE, but not both. |
! $a | Not | TRUE if $a is not TRUE. |
$a && $b | And | TRUE if both $a and $b are TRUE. |
$a || $b | Or | TRUE if either $a or $b is TRUE. |
Aritmetic Operators
Just what it says – this is basic math.Example | Name | Result |
---|---|---|
$a + $b | Addition | Sum of $a and $b. |
$a – $b | Subtraction | Difference of $a and $b. |
$a * $b | Multiplication | Product of $a and $b. |
$a / $b | Division | Quotient of $a and $b. |
$a % $b | Modulus | Remainder of $a divided by $b. |
Loops
Loops are really handy. They let you program your code to repeat itself (and also to figure out how many times to run through itself before it’s done). Loops have instructions to “keep running this piece of code over and over again until certain conditions are met.” You can use more than one kind of loop. Let’s look at the most basic kind, the “while” loop.The while loop says,
01 | while (something is true ) |
02 |
03 |
04 |
05 | { |
06 |
07 |
08 |
09 | // do something that you specify |
10 |
11 |
12 |
13 | } |
So if you wanted a script to print the numbers from 1 to 10, you can tell it (this is English, not PHP here):
01 | a. the variable $MyNumber = 1; |
02 |
03 |
04 |
05 | b. print $MyNumber; |
06 |
07 |
08 |
09 | c. add 1 to $MyNumber; |
10 |
11 |
12 |
13 | d. go to sep a. and run this script again with the new value of $MyNumber; |
14 |
15 |
16 |
17 | d. stop when $MyNumber reaches 11; |
$a++; | adds 1 to the value of the variable $a each time through |
$a–; | subtracts 1 from the value of the variable $a each time through |
|
|
- line 1: start PHP code;
- line 3: set variable $MyNumber to 1;
- line 5: initiate “while” loop: while the variable $MyNumber is less than or equal to 10, execute what’s below; otherwise move on;
- line 9: print the current value of $MyNumber;
- line 11: add 1 to the value of $MyNumber;
- line 15: end PHP code.
Other Loops
PHP has other kinds of loops, but they are beyond the scope of this tutorial. If you want to learn what they are and how to use them, follow these links to PHP.net:Functions
If you’ve used HTML a lot, you know that it’s a pretty limited language that was designed back in the dark ages before we all knew what the Net was capable of.PHP, however, is very flexible. Not only does PHP have a library of canned functions that’ll do everything from sorting stuff in alphabetical order to sending email, from connecting with databases to balancing your spaceship’s inertial sub-space dampers, but you can also create your very own functions to do all manner of things related to your website. The functions you create get executed exactly like those from the PHP library, but they’re your own. In the following section, I’ll show a glimpse of how you create your own functions and feel the power.
Functions you create are like little machines that do something for you. You construct them and then call them as needed.
You’ll remember that the very first thing we learned to do was a simple “print” statement, which followed the form:
1 |
|
2 |
3 |
4 |
5 | print ( "whatever it is I want to show up on-screen" ); |
6 |
7 |
8 |
9 | ?> |
01 |
|
02 |
03 |
04 |
05 | function MyFunction () |
06 |
07 |
08 |
09 | { |
10 |
11 |
12 |
13 | statements that make up the function ; |
14 |
15 |
16 |
17 | } |
18 |
19 |
20 |
21 | ?> |
Then you define the rules of the function inside the following curly brackets (that’s { and } on lines 5 and 9). Don’t you just love the words “curly brackets?”
Let’s walk through the making of a couple functions. Functions come in two flavors, those that require “arguments” and those that don’t. An “argument” is a variable that comes from outside the function, but which the function needs in order to run.
Let’s first look at one that doesn’t require arguments:
01 |
|
02 |
03 |
04 |
05 | function ChickenMan() |
06 |
07 |
08 |
09 | { |
10 |
11 |
12 |
13 | print "I am the CHICKEN MAN!" ; |
14 |
15 |
16 |
17 | } |
18 |
19 |
20 |
21 | ChickenMan(); |
22 |
23 |
24 |
25 | ?> |
line 3: create function ChickenMan;
line 5: start definition of function ChickenMan;
line 7: definition of ChickenMan is to print “I am the CHICKEN MAN!” inside and tags;
line 9: end definition of ChickenMan;
line 11: call function ChickenMan (meaning “do the thing that we defined the function to do”);
line 13: close PHP;
Any place in this web page that you put “ChickenMan();” inside the tags, it’ll print your little statement. See how this saves you time if you want to print this string a bunch of times in different places?
Now let’s get a little more complicated and create a function that does take arguments. Say I’m a loan shark and I’m going to loan you the money to buy that personal hovercraft you’ve been lusting after. I’ll lend you however much you need, but you have to pay me 14 percent interest per week or I break your legs.
I’ll create a function called InterestPayment which calculates your weekly payments (until you pay off the whole loan amount in one lump sum).
First we’ll create a form page where the user enters how much of a loan he or she wants. The user enters the hovercraft’s sticker price, and that number gets passed along from the form as a variable called font size="2">$Cost. (For the HTML behind this, go here.)
Next, our function will take the amount that the user enters into the variable font size="2">$Cost and spit back 14 percent of that amount, which is how much the hapless borrower owes every week. This will happen in the PHP page titled “loanshark.php” that the form page points to (it points with this code: