A Tiny PHP Tutorial
PHP is a server-side scripting language that you can use to customize the content of web pages. In this mini-tutorial, you will see how to use PHP to customize the contents of a web page by using information from a form. To give us a concrete example to work with, we will assume a web page has the following form on it:
Here is what the XHTML for that form looks like (approximately):
This form will send two name-value pairs to a script named login.php, one named email, and the other named password.
The form above actually has a different value for its action attribute from what is shown. Instead of sending the form data to scripts/login.php, it actually submits the form to this web page (). You can see the form in action by filling it in, clicking the Login button, and looking at the paragraph below, which was generated by a PHP script embedded in this page. Try changing the contents of the form’s input fields and seeing the changes in the paragraph when you resubmit the form:
And here is what the PHP script that generated the text in the above paragraph looks like:
The first thing to note is that PHP code has to be inside a tag that starts with <?php and ends with ?>. There can be multiple instances of this tag on a web page if you want to use PHP to generate different parts of a page. For example, I can tell you that today is because I inserted the date into this sentence using a second piece of PHP code, in addition to the one that generated the contents of the paragraph showing the form data earlier.
The next thing to note is that PHP code is different from XHTML and CSS in a special way: XHTML marks up different parts of a web page’s contents, and CSS provides rules for what different parts of a web page are to look like, but PHP consists of a sequence of statements that perform actions. Statements get executed one after the other. Each one has to end with a semicolon.
In the code above, the statements all start with the keyword echo. Echo statements (do not capitalize the keyword; PHP, like most computer languages, is case-sensitive) cause the program to generate content into your web page. Echo statements consist of the keyword, echo, a string of text inside quotes, and finally a semicolon at the end of the statement.
The remainder of the PHP program is not part of the web page: the <?php, ?>, and everything in between gets removed from the web page before it is returned to the browser. View the source code for this web page, and you will see no PHP code, only the XHTML and text content that I typed plus the XHTML and text content that were generated by PHP echo statements, and there is nothing in to indicate which is which.
Variables
PHP programs use named variables, things that have names and can hold values, to get their interesting work done. As the word “variable” implies, the value of a variable can change. For example here are some PHP statements that show the kinds of thing variables can do:
There are rules for naming variables in PHP: the first character has to be a dollar sign, and the rest of the characters can be a mix of letters, digits, and underscores. Variable names are case-sensitive. The variable names $foo, $bar, and $baz in the example are sort of like lorem ipsum text: they are meaningless names that are used by convention when you don’t want to make up meaningful names. In real programs, you try to pick names for variables that tell what they are being used for.
You can assign a value to a variable by putting the variable name on the left side of an equal sign and the value you want to assign to it on the right side of the equal sign. This kind of statement is called, not surprisingly, an assignment statement. The equal sign is an active thing: it doesn’t say that the left and right sides are the same thing, it says that as a result of executing the statement, the left side will have the value of the expression on the right. So the fourth statement above changes the value of $baz to be one less than what it was before the statement was executed.
Strings
PHP strings are pieces of text enclosed in single or double quotation marks. You can refer to simple variables inside strings that use double quotes, and the value of the variable will get interpolated into the string. So the sample code above would generate a paragraph that says, “The answer is 7.”
You can put strings together using dots to connect them. So "hello, world" is the same as "hello" . ", wo" . "rld", an admittedly lame example but technically correct. Before we see why you need to know about this, we need to talk about …
Arrays
Arrays are lists of values. All the elements in the list have the same name, and the different ones are identified by subscripts, which can be either numbers or strings (or variables that hold numbers or strings!) enclosed in square brackets. Here is an example:
The first statement made the variable $foo into an empty array. The next two statements assigned numeric values to the first two elements of the array (by convention, subscript values start at zero, but you can use any numbers you like, including negative ones), and the last statement uses one string for the subscript (favorite-food), and another string for its value (apple pie).
Arrays are considered a somewhat advanced topic, but we need them to process our form data because the name/value pairs from the form are made available to a PHP script in a pre-defined array. If the form method is get, the name of the PHP array is $_GET, and if the form method is post, the name of the PHP array is $_POST. The subscripts for the array are the form data names, as strings, and the values of the array elements are the corresponding form values.
So for the form at the top of this page, if you typed secret into the password field, which has name="password", the PHP program will find that the value of $_GET['password'] is the string "secret".
Interpolating array values into strings
If you try to interpolate a reference to an array value into a string, such as <?php echo "The value is $_GET['password']"; ?>, it will not work. An easy way to fix the problem is to connect the string parts using dots: <?php echo "The value is " . $_GET['password']; ?>. There are other ways to do it, but at this stage, one technique that works should be sufficient.
Control Statements
The sample code uses what is called a control statement to make decisions about what to echo based on the values of variables. This particular control statement uses the keywords if and else. The generic syntax rule for this sort of statement is:
Note that control statements don’t get a semicolon at the end of them.
Following the if is an expression inside parentheses, which is evaluated to be either true or false, which can be done using the === comparison operator. In the sample code, ($_GET['email'] === "") is used to test if the value the user typed into the email field of the form is equal to an empty string (nothing between the two double quotes), producing true if the user typed nothing and false if the user typed anything at all.
Following the if (expression) part, comes a block of one or more statements surrounded by curly braces ({ … } that will be executed if the value of the expression is true. After that comes the keyword else and another block of statements inside curly braces that will be executed if the value of the expression is false. The else and its block of statements can be omitted if they aren’t needed.
The sample code for processing the form data shows a “nested if” structure: the true part of the first if contains two entire if—else statements inside its true block of statements. The nesting rules are much like those for XHTML tags: the inner statements must be completely contained inside the outer one and must not overlap each other.
Functions
There is one more feature of PHP that has to be mentioned, and that is the use of functions. Like variables, functions have names (except they do not start with dollar signs). Functions can be used as expressions that take arguments and may return a result. For example, the PHP expression sqrt(2) passes the value 2 as an argument to a function named sqrt; this function computes the square root of whatever argument is passed to it, and in this case returns the value . (Could you guess that I let PHP “type” that number for me by inserting <?php echo sqrt(2); ?> into the previous sentence?)
Functions can return logical values, strings, or numbers. In the sample code, the function named isset() is used to generate a logical value for the first if statement, if (isset($_GET['email']) … . The problem solved by this if test is that $_GET['email'] only exists if the web page is actually invoked from a form that uses the get method and has a data value named email, and PHP will generate an error message if you try to access a variable that has not been assigned a value. The isset() function returns true if its argument has actually had a value assigned to it and false otherwise, such as when you first loaded the page instead of submitting the form.
Functions can also return other things. For example the function named array(), shown earlier, returns an empty array that was assigned as the value of the variable $foo.
One of the things that makes PHP so popular is the large number of functions that are built into the language: they are pieces of code that you can use to get a lot of work done without having to develop the code yourself. The down side of this feature is that just learning what functions are available is a significant piece of work. They are all well-documented, and a lot of the process of becomming a PHP programmer is getting familiar with them by looking them up in the PHP online documentation.
Summary
PHP is a rich programming language, and you cannot expect to master it all at once, but this page has introduced several key features of the language, enough that you should be able to generate a web page with content tailored to data sumbitted to it from a form.