July 27th, 2010 §
This assignment is meant to give practice to the most important parts of PHP besides database integration, which is addressed in separate assignments. The core concepts are include files and passing data (a.k.a. persistent data) using forms, links, and cookies.
Your assignment is to make a site consisting of four web pages:
- Home (index.php)
- News (news.php)
- Contact Us (contact.php)
- Thank You (thank_you.php)
There will also be multiple other files that the user never sees directly. These will be:
- process_name.php (process the data the user enters on the Home page)
- process_contact.php (process the data the user enters on the Contact Us page)
- _article1.php, _article2.php, _article3.php, etc (the XHTML snippets for each article linked to from the News page)
Home (index.php)

Home page
Global navigation. The Home page, like every other page on the site, has a top navigation menu with links to Home, News, and Contact. This menu should use the technique of creating horizontal menus from list tags. The global navigation should be created as a separate file so it can be included on all other pages of the site in a templatized manner.
Form. The Home page also has a form the user can fill in with their first and last names. This form should submit the data the user enters to a script file called process_name.php via the HTTP POST method, which does something with that data.
The code for the form will probably look something like the following. Note the action and method attributes of the form tag and the name attributes of the two form input elements. These are all important and you must understand why they are there:
<form action="process_name.php" method="POST">
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" />
<br />
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" />
<br />
<input type="submit" value="Enter site!" />
</form>
process_name.php
When the user clicks the submit button on the form on the Home page, the data they entered is sent along with the HTTP POST request for the file, process_name.php.
process_name.php should take the first name that the user entered in the form and store it semi-permanently in a cookie. Setting a cookie is handled by PHP’s built-in setcookie() function.
Once that is done setting the cookie, this script should redirect the user to the News page (news.php). Redirecting is done using PHP’s built-in header() function, which allows you to send customized HTTP headers from the server to the client.
News (news.php)

News page
Global navigation. The News page, like the Home page, includes the global top navigation from the external file.
Reading the cookie. The News page also reads the cookie which has the user’s first name in it. To read a cookie, you can use PHP’s built-in $_COOKIE associative array.
News articles. Each article title in the list of articles titles on the left side of the News page should be a link to news.php. Along with each link, we will be passing the id of the article the user clicked on using the technique of passing data via links.
The XHTML for the article links will look something like the following. Notice how each link passes a different article_id parameter in the query string:
<ul>
<li><a href="news.php?article_id=1">article title 1</a></li>
<li><a href="news.php?article_id=2">article title 2</a></li>
<li><a href="news.php?article_id=3">article title 3</a></li>
</ul>
Loading the correct article. The News page is therefore a template that can be used to load up any article, depending which link is clicked. So, obviously, the code must somehow determine which article to load up.
In the code from the example linked above, you’ll see that we find out which article link was clicked by the user by looking for the article_id parameter that was submitted along with the request for the news.php page in the query string in each link.
$articleId = $_REQUEST['article_id']; //get the article id from the browser's request data
//check to make sure there is an article id that was requested
//is_numeric() is a built-in PHP function that checks to make sure a variable is a number
//the ! is a logical NOT, so this statement says "if the article id is NOT a number, do the following:"
if (!is_numeric($articleId)) {
//if there was no article id requested, use the number 1 as a default
$articleId = 1;
}
Then, depending on which article id was requested, in the body of the XHTML document on the news.php page, we load up a different include file with the correct article content in it.
//load up the article that was requested from the external article content files
if ($articleId == 1) {
//include an external XHTML snippet into this template
include("_article1.html");
}
elseif ($articleId == 2) {
include("_article2.html");
}
elseif ($articleId == 3) {
include("_article3.html");
}
//...and so on for all the other articles
Contact Us (contact.php)

Contact Us page
Global navigation. The Contact Us page includes the global navigation the same way as the other pages.
Article links. It also has the set of article links on the left side of the page, the same as on the News page. These should each link to news.php and pass along their corresponding article_id parameters, exactly as described for the News page.
Contact form. The form allows the user to send an email to the site administrators. When a user fills out the form and clicks submit, the form sends a request for the script, process_contact.php, which handles sending the email.
process_contact.php
process_contact.php, like process_name.php, is invisible to the user – the user never sees it directly. This script takes the data that the user entered into the form on the Contact Us page, and sends it in an email to the site administrators.
Once the email has been sent using PHP’s built-in mail() function, the script then redirects the user to the Thank You page (thank_you.php) using PHP’s built-in header() function, the same way we did it on process_name.php.
Thank You (thank_you.php)

Thank You page
Global navigation. This page uses the same global navigation links and same article list as seen on the other pages.
Thank you message. The main content of this page is a message thanking the user for submitting the Contact form.
<form action="process_name.php" method="POST">
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name" />
<br />
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name" />
<br />
<input type="submit" value="Enter site!" />
</form>
April 18th, 2010 §
Working off of the example code from the Basic SQL example files, here is a slightly more sophisticated set of pages that when used together, create a sort of Content Management System for our animals application.
How it works
Here is a user flow diagram outlining how this application fits together. Below the diagram is an overview of each step.

User flow diagram for Basic SQL CMS
read.php
In this version of the files, the pages that handle each of the CRUD commands are all linked together. A user can view the animals stored in the database on the main page, read.php. Read.php simply queries the database for a list of all the rows stored in the animals table, and outputs each of those rows into the XHTML for the page.
The user can click links to “update” or “delete” any individual animal. When they click either of those links, the id of the selected animal is passed in the query string of the link to the corresponding page, either update.php or delete.php.
update.php
Update.php displays a form that the user can use to change the name of the animal that was clicked. The first time this page is loaded, this form is prepopulated with the existing name of the animal that was clicked, which has been retrieved from the database.
The id of the animal and its new name are passed along with another request for update.php once the user clicks the submit button. Update.php this time updates the selected row in the animals table and redirects the user back to read.php, where the user can see the updated list of names.
delete.php
Delete.php simply runs a query that deletes the selected row from the database, and then redirects the user to read.php, where they can see the updated list of animals.
create.php
A user can click a link to “add a new animal” on read.php. This takes them to create.php, where they can enter a new animal name into a form. When they submit the form, the animal name is passed along with another request for create.php.
Create.php this time creates a new row in the database table for the new animal, and then redirects the user to read.php, where they can see the updated list of animals.
April 11th, 2010 §
One potential problem that you may come across when putting XHTML code inside your PHP files is that the XML declaration tag may confuse the PHP server.
Short tags
Some PHP servers, including ours, are set up to accept “short tags”, which are shortcut versions of some PHP commands. For example, on our server, you can either open your PHP script by writing
<?php
Or you can simplify that to
<?
This is a shortcut, “short tag” version of the opening PHP tag that allows lazy developers to type less.
There is another short tag that replaces the normal “echo” command. For example, a normal echo might look like
<?php echo "arugala"; ?>
And the shortened version of the same command would be
<?= "arugala"; ?>
The problem
A problem arises when we put XHTML code inside a PHP file (a file with the .php extension) because the “xml” tag that we use as the first line of our “bare minimum” XHTML document includes the “<?” in it.
<?xml version="1.0" encoding="utf-8"?>
This confuses the PHP processor, which thinks you intend to use a PHP short tag, which you do not. You will an error message about a “parse error”.
See this problem in action
The solution
The solution is to encapsulate the “<?” characters inside of a PHP echo statement. This way you prevent the PHP processor from thinking that those two characters are the start of a PHP opening tag.
<?php echo "<?"; ?>xml version="1.0" encoding="utf-8"?>
See this solution in action
Why you should use PHP short tags
You may be tempted to use PHP short tags. The conventional wisdom is that it’s a bad idea. This is because not all servers are set up to support them.
So if you at some point move your code from a server that does support them to a server that doesn’t, your code will cease to work.
This does not fit in with our philosophy of writing code using only those practices that are guaranteed to work with a minimum of fuss.
December 12th, 2009 §
December 5th, 2009 §
Let’s say that we are building a social network. What we call a social network is a site that has a bunch of users, and those users can decide to be “friends” with any other user.
You can view this example live here.
The Views
There will be four pages that the user sees:
- Register – where new users go to register to become users
- Login – where registered users go to login
- Home – a page that shows a list of the logged-in user’s friends, and a list of people who are not his/her friends.
- Friends’s Profile – a page that shows details about another user
Each “page” requires a View in order to be displayed to the user in the browser. Anytime there is something displayed to the user, we should know that there is at least one View used to create that interface. So we can say that there are four Views in this application. In our example application, the files that contain the templates for these Views are:
- views/register_view.php – the template for the Register page
- views/login_view.php – the template for the Login page
- views/index_view.php – the template for the Home page
- views/profile_view.php – the template for the Friend’s Profile page
The Controllers
- We only want to let a user go to the Login page if they are not already logged in. If they are already logged in, we need to redirect them to the Home page. Anytime we have a script that performs some logic like this, we should consider it a Controller.
- Likewise, a user should only see the Register page if they are not already logged in. Again, this logic is handled by a Controller.
- Assuming a user is not already logged in, when they enter their username/password in the form on the Login page and click the submit button, there has to be some script that performs the logic to compare the username/password data the user entered in the Login page to the user data stored in the database. If the username/password matches what is found in the database, this script has to let the user in to the site. This logic is the job of a Controller
- Likewise, when a user fills out the Register form and clicks submit, a script has to check to make sure they entered a valid username/password, and then if everything is ok, the script has to somehow create a new row in the database that stores that username/password. Then the user should be redirected to the Home page. This business logic is the job of a Controller.
- The Home page needs to check to make sure the user is logged in. It then needs to retrieve the list of friends of the logged-in user, the list of people who are not friends of the logged-in user, and then display that data to the user. The decision of what data to retrieve from the Model, and the job of then forwarding that data to the View which displays the interface, is the job of a Controller.
- The Friend’s Profile Page has the same type of Controller as the Home page. Data must be retrieved from the Model, and then that data must be properly inserted into the View for this page. So a Controller must be present to take care of this.
The Controller scripts that I have created for this application to handle these tasks are:
- authenticate.php – handles all tasks related to Login and Register functionality
- index.php – handles all tasks related to viewing the Home page
- profile.php – handles all tasks related to viewing a Friend’s Profile
- friendship.php – handles all tasks related to adding/removing friends
The Models
As should be clear by now, Models are necessary to handle the parts of this site where direct access to the database is needed:
- compare any username/password combo to those already stored in the database (necessary for the Login and Register pages)
- create a new user in the database (necessary for the Register page)
- create/delete friend associations in the database (necessary for the Home and Friend’s Profile pages)
- get a list of a user’s friends (necessary for the Home and Friend’s Profile pages)
- get a list of people who are not a user’s friends (necessary for the Home and Friend’s Profile pages)
The Model scripts that do these tasks are:
- models/User.class.php – handles any tasks related to creating, reading, updating, or deleting users
- models/Authentication.class.php – handles any tasks related to logging in or registering a user
- models/Friendship.class.php – handles any tasks related to friendships between two users
- models/Santize.class.php – handles any tasks related to data sanitization
To be consistent and complete, I have added the standard CRUD functions to each Model script, as well as the functions which handle each of the database-related tasks listed above.
It’s object-oriented
You can see that I have created seperate class files for each Model. I am combining MVC architecture concepts with object-oriented programming techniques. I have created classes for each type of “object” or “entity” that I think may conceptually need specific actions taken on it.
Object oriented programming is a seperate concept from MVC architecture. But I have used this example to exhibit both.
It uses a home-brewed framework
You can see that I have organized my code in a specific way. All Model files are contained in the models/ folder. All View files are contained in the views/ folder, and all Controller files are contained in the root folder. Javascript files would go in the scripts/ folder. Style sheets are in the styles/ folder, and database connection info is in the dbinfo/ folder.
One of the core features of a so-called “framework” is a clear organization of the files involved in a project. So you could call this organization that I have come up with a sort-of home-brewed framework. It is very simple, and crude, but it is effective at helping organize our MVC object-oriented application.
The popular frameworks that PHP developers use, such as Zend, CakePHP, Symfony, and CodeIgnigter, do much more sophisitcated things than just seperate your code into folders. So I doubt my framework will become the next big thing. But it is useful for our purposes nonetheless.
What the user sees
It’s important to note that the users will be completely oblivious to our use of an object-oriented MVC architecture. This is a good thing: you don’t want users to have to worry about how a site was developed.
When a user goes to the Login or Register pages, they will see the address authenticate.php in the browser address bar. This is the Controller script that we know handles all tasks related to logging in and registering. This controller figures out whether the user wants to see the Login Page or the Register Page, and loads up the appropriate View for either page.
When a user goes to the Home Page, they see the address, index.php. This, as we know, is the Controller file for the tasks related to the Home page. This Controller calls functions in the Model that get the data related to the Home page, and then this Controller loads up the View file for the Home page, which displays this data nicely.
Similarly, when a user goes to a Friend’s Profile page, they see the address, profile.php in the browser’s address bar. This is the Controller file for all tasks related to viewing the Friend’s Profile page. This script gets all the data by calling functions in the Model, and then includes the appropriate View file to display that data.
November 23rd, 2009 §
In your readings, you may have come across mention of PHP Sessions. Sessions are another mechanism, in addition to the $_GET, $_POST, and $_COOKIE variables that allow you to “maintain state”, meaning to pass data from one page to another.
Session variables are just like cookies, but easier
PHP provides a set of functions that allow you to read and write session variables. The basic idea is that session variables allow you to store data for as long as the user’s session is still alive. Generally, a session is alive as long as the user’s browser is open, just like cookies. These session variables can be accessed from any page on the site, just like cookies.
These are variables that are stored on the server, and last for a limited amount of time. They are functionally very similar to cookies, and in fact PHP does use cookies to perform most of the tasks involved with Sessions. But PHP hides the internal details of how Sessions work, which makes your job a little bit easier.
How to use sessions in PHP
Any script that uses session variables, either to read or write them, needs to call the session_start() bult-in PHP function at the top of the script. This is just a command to tell PHP that you want to use sessions on this page.
Once you have done that, you can create a session variable like this:
//create a session variable called "test_variable"
$_SESSION['test_variable'] = "this is the value of the test variable";
Once you have created a session variable, any other page on your site can access that variable like so:
//echo the value of the session variable called "test_variable"
echo $_SESSION['test_variable'];
Example Files
Here is an example of a script that writes a session variable, just like the example code above.
And this page reads that same variable and outputs it to the page.
Further reading
Here are some pages that cover sessions, and explain how to write PHP code to deal with them:
http://php.about.com/od/advancedphp/ss/php_sessions.htm
http://www.tizag.com/phpT/phpsessions.php
http://www.htmlgoodies.com/beyond/php/article.php/3472581
http://us3.php.net/session
November 23rd, 2009 §
As a general rule, any data that comes from a user is not to be trusted. So anytime you are dealing with data that may (or may not) have originated from a user, you need to sanitize that data before doing anything else with it. Think of it as basic web hygiene, akin to washing your hands in the restroom. Quoting Google’s CEO, Eric Schmidt, the intenet is a “cesspool”. None of us needed him to tell us that – it’s obvious.
Anytime your site deals with data that does not originate from your own code, you need to sanitize it before letting it touch the internal organs of your website. When we talk about sanitizing, we’re not talking about removing bad words from the code, we’re generally talking about preventing malicious hackers from trying to break into our website by sending data to the server that may allow them to exploit faults in our code or weaknesses on the server.
User-generated content may often come from any of the following sources:
Practical sanitization
No need to get paranoid yet. For our practical purposes, any data that you get from the $_REQUEST, $_GET, $_POST, or $_COOKIE arrays should be sanitized.
Let’s say you have code like this:
$dummyData = $_REQUEST['dummy_data'];
This is getting data from the $_REQUEST variable, which as we know is automatically populated with data from the query string in links, from form fields, or from cookies. In other words, it’s potentially tainted. And let’s say you are planning to store that $dummyData in a database table like so:
$myQuery = "INSERT INTO abloomberg_dummy (data) VALUES ('{$dummyData}')";$result = mysql_query($myQuery);
You absolutely must sanitize it to prevent malicious things like SQL injection attacks before you run that query.
An example
This example uses PHP code to do just that. It uses an object-oriented Sanitize class (as in classes and objects in object-oriented programming) that I based off of another well known (but not object-oriented) script.
To use this Sanitize class in your own PHP scripts, before you do anything else:
- download a copy of the zip archive, unzip it, and put the file Sanitize.class.php in the folder for your project.
- make sure your script includes this file by using require_once(“Sanitize.class.php”);
Once you have that set up, you’re ready to use this class. Here is an example usage:
<?php //file: index.php //an example of using the Sanitize class
//include the Sanitize class into this script require_once("Sanitize.class.php");
//on a live site, you'd want to sanitize all data that you got from the user //in otherwords, any time you use data you got frm the $_REQUEST, $_GET, $_POST, or $_COOKIE variables //For example, if the data was coming from a form or query string in a link: //$dirtyData = $_REQUEST['something'];
//in this example, for simplicity, i'm just sanitizing the contents of a variable that's hardcoded $dirtyData = "this is a test with an HTML tag <a href='#'>click me</a>";
/* First choose how you want to santize the data. The choices are: (PS: notice that these are static properties of the Sanitize class - hence the :: symbol)
Sanitize::HTML //replaces any HTML tags with "HTML entities" Sanitize::SQL //prevents against SQL injection attacks Sanitize::UTF8 //makes sure data is in UTF8 format Sanitize::INT //makes sure the data is an integer Sanitize::FLOAT //makes sure the data is a float (decimal) Sanitize::LDAP //prevets against any LDAP code Sanitize::SYSTEM //prevents any system commands from being run Sanitize::PARANOID //all of the above */
//set the $flags variable to be the sum of all the flags you want to use from the list above $flags = Sanitize::HTML + Sanitize::SQL; //this example removes any HTML or SQL commands from the string
//now pass the data and the $flags variable to the sanitize function to sanitize it $cleanData = Sanitize::sanitize($dirtyData, $flags); //call the static method "sanitize of the Sanitize class
//now your data is clean echo $cleanData; //the text stored in this variable has been "sanitized"
//you may want to "view source" in the browser to see what happened to the text?>
Understanding the Sanitize::sanitize() method
The most important part to understand is the command that actually does the sanitizing:
$cleanData = Sanitize::sanitize($dirtyData, $flags); //call the static method "sanitize of the Sanitize class
This line calls the Sanitize::sanitize() function and passes it two arguments: the data to be sanitized, and the flags that indicate what type of sanitization you want to do. The result of this sanitize() function is then put into the variable $cleanData, which now has the sanitized version of the data.
In this example, we have set the $flags variable to indicate that we want to remove any HTML or SQL code from the data:
$flags = Sanitize::HTML + Sanitize::SQL; //this example removes any HTML or SQL commands from the string
We can use any combination of the available flags by adding them together.
Now that the data has been sanitized, you can safely store that data in a database without worrying about SQL injection attacks:
$myQuery = "INSERT INTO abloomberg_dummy (data) VALUES ('{$cleanData}')";$result = mysql_query($myQuery);
Or do whatever else you want with it. But rest assured it does not have any malicious HTML or SQL code in it.
Note that since this example is object oriented, we never have to look at the source code of Sanitize.class.php. This is abstraction at work.
November 6th, 2009 §
Understanding how to use the $_GET, $_POST, and $_REQUEST variables is critical to creating a site in PHP. So here is an in-depth analysis of how data is passed from one page to another using forms.
In our earlier post, we discussed the concept of persistent data. Each web page is like a distinct application that does not share any information with any other web page. But sometimes, you want one script to communicate with another script. Sometimes two different pages need to share data.
In this post, we’re going to take a look at three things:
- an XHTML form in which a user will enter some data
- the HTTP request, which is the technical mechanism the browser uses to send the data the user entered in the form to the server
- the way a PHP script can access the data the user entered in the form and do something with it
The example scenario
As an example, let’s say we have created a website where users can sign up to receive a free guide to Sri Lankan real estate in the mail. So there is a form that the user has to fill out where they enter their shipping address. When the user clicks the “submit” button on that form, that data that they entered is taken from the page on which they entered it, and is sent to another script using either a GET or POST request to the server.
These two types of HTTP requests, GET and POST, are the primary ways that a browser can make requests pages from a server. (For an overview of all possible types of requests and responses between web clients and servers, you can look up the HTTP reference page on Wikipedia).
index.php, the XHTML file
Let’s imagine that index.php is the XHTML code for the form where the user enters his shipping information. This form just has a bunch of text fields that a user fills in with his shipping address. Then the user clicks “Send it now!” to submit the form:
<form action="process_signup.php" method="POST">
<label for="full_name">Name:</label>
<input type="text" id="full_name" name="full_name" />
<br />
<label for="street">Street:</label>
<input type="text" id="street" name="street" />
<br />
<label for="city">City:</label>
<input type="text" id="city" name="city" />
<br />
<label for="state">State:</label>
<input type="text" id="state" name="state" />
<br />
<label for="zip">Zip:</label>
<input type="text" id="zip" name="zip" />
<br />
<input type="submit" value="Send it now!" />
</form>
When viewed in the browser, and surrounded by the usual <html>, <head>, and <body> tags, this page, without any style sheets, will look something like this:

A simple form
The HTTP POST request
When the form is “submitted”, what this means in technical terms is that the browser actually makes an HTTP POST request to the server for the file, process_payment.php. We can tell this because the <form> tag has two attributes: “action” and “method”, which indicate what the browser should do when the user clicks the submit button.
<form action="process_payment.php" method="POST">
The “action” attribute indicates which page the browser should request when the user clicks submit. The “method” attribute indicates which HTTP type of request the browser should make. In this case it’s a POST request.
The POST request asks the server for the process_signup.php file, but along with that request it also sends the data the user entered in the form to the server. That data is sent in a way that is invisible to the user, hidden in the HTTP headers that the browser uses to make the formal request the server for the process_payment.php file.
If we were to somehow intercept those invisible headers that the browser sends as its formal request to the server, they would look something like this:
POST /process_signup.php HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded
full_name=Amos+Bloomberg&street=145+4th+Avenue&city=New+York&state=NY&zip=10003
The top part are the generic HTTP POST headers indicating what file the browser wants, and what kind of client the browser is. The bottom line contains the urlencoded data that the user entered in the form. This is how POST method submits data to the server. But you’ll never see any of that since it is never shown to the user.
Notice that the data in the bottom line holds the data that the user entered as a series of key=value pairs, with a very specific syntax:
key1=value1&key2=value2&key3=value3 ... and so on...
In urlencoding, all key/value pairs are separated by ampersands, “&”. The key to each piece of data from a form is always the “name” attribute of the XHTML form field in which the user entered the data. The value is always the text that the user entered.
So “full_name” is what we put in the “name” attribute of the first <input> tag in the form…
<input type="text" id="full_name" name="full_name" />
..so that’s the term that is used as the key to that piece of data in the HTTP POST request that is sent to the server.
full_name=Amos+Bloomberg&street=145+4th+Avenue&city=New+York&state=NY&zip=10003
“street” is what we used as the “name” attribute of the second <input> tag in the XHTML, so that’s what is used as the key to the second piece of data in the HTTP POST request. And so on for all the other form fields.
process_signup.php, the PHP script
Once that form has been submitted and the HTTP POST request has been made to the server, the server sees that the file that the browser requested is a PHP script, so it runs that script on the server before sending anything back to the client.
PHP, since it is built specifically for the web, is smart enough to know that the PHP code in the scripts on the server might be interested in the details of the data that was sent along with the HTTP request, meaning the data that the user entered in the form. So PHP provides a few special variables that contain that data in an easy-to-use format.
The $_POST variable is built-in associative array that automatically is set to hold all of the data that was sent along with in any HTTP POST request to the server. The index of each element in the associative array is the same word that was used as the key in the key=value pair that represented that data in the HTTP request. This is also, if you recall, always the same word as the “name” attribute of the form field in which the user entered the data.
So in our example, the $_POST array will have 5 elements. If we were to dump out the raw data stored in the $_POST array in our PHP script using the built-in print_r() function, which we always use to debug arrays, it would look something like this:
Array(
full_name => Amos Bloomberg,
street => 145 4th Avenue,
city => New York,
state => NY,
zip => 10003
)
We can access each element in the array individually in PHP by using the $_POST array with the correct term as the index, using the syntax $_POST['<index name>']. For example:
$fullName = $_POST['full_name'];
$street = $_POST['street'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
The important thing is that the index that we use each time we access the $_POST array is the same word that we used in the “name” attribute of the form field <input> tag in the XHTML page where the user entered their address.
Assuming all the names we use as indexes for the $_POST array in the PHP match the “name” attributes of all the form fields the user filled in on the XHTML page, we will have successfully passed data from one page to another. Data the user entered from the form has been passed to the PHP script.
Assuming the XHTML “names” and the PHP indexes match, we will now have the data that the user entered in the form stored in our variables, $fullName, $street, $city, $state, and $zip. And we can do whatever we want with that information, for example storing it in a database, or sending it in an email to someone.
The HTTP GET request
As an alternative, we could have used the HTTP GET method instead of the POST method when submitting the form. To do this, we would have changed the form tag in the XHTML to be:
<form action="process_payment.php" method="GET">
The practical difference between the two is that with GET, the data that the user enters in the form is attached to the URL of the file that the client is requesting from the server. And users will see the data they entered in the form show up in the address bar of the browser, when it requests the file process_signup.php, so data passed along with a GET request is not invisible or hidden from the user.

Browser address bar with HTTP GET request data
If we were to intercept the headers in an HTTP GET request to the server, it would look something like this:
GET /process_signup.php?full_name=Amos+Bloomberg&street=145+4th+Avenue&city=New+York&state=NY&zip=10003
Host: www.mysite.com
User-Agent: Mozilla/4.0
Notice how the data the user entered in the form is tacked on to the end of the file name that the browser is requesting from the server. The user will see all this data in the browser address bar as well.
Just as the data sent along with the POST request to the server in our original example was automatically stored in a $_POST variable in the PHP script on the server, process_signup.php, the data sent along with the GET request is automatically stored in a $_GET variable. And you can access that data in almost the exact same way you did with the $_POST variable in your PHP code:
$fullName = $_GET['full_name'];
$street = $_GET['street'];
$city = $_GET['city'];
$state = $_GET['state'];
$zip = $_GET['zip'];
So, as I hope is obvious, the $_GET variable only holds data that was passed to a PHP script via the GET method. And the $_POST variable holds only that data that was passed to the server via a POST request. Do not try to mix and mingle the two.
The $_REQUEST variable
Whereas the $_GET variable only holds data passed to the server with an HTTP GET request, and the $_POST variable only holds data passed to the server in an HTTP POST request, the $_REQUEST variable holds any data passed to the server along with either type of request. It also holds data passed via cookies.
The $_REQUEST variable is a sort-of catch-all for any data passed to the server, regardless of how it got there. So regardless of whether the form used the method POST or the method GET, we could use this code in the PHP script to access the data:
$fullName = $_REQUEST['full_name'];
$street = $_REQUEST['street'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$zip = $_REQUEST['zip'];
As you can see, the built-in $_REQUEST variable is an associative array with indexes that are the same words we used in the “name” attribute of each field in the XHTML form, just as $_POST and $_GET were.
November 1st, 2009 §
To complete the templatizing assignment from Class 6, you will need to have a good understanding of arrays. This post is meant to be read in addition to the readings from the assignment post, to give you an introductory description of arrays to help you think about arrays clearly.
Simple arrays
An array is a list of data. In its simplest form, each element in the list consists of two bits of data: a key and a value. So you can think of an array as a table with two columns: one for the key, and the other for the value of that element in the array.
For example, we could conceptually think of an array containing a shopping list as follows:

An array holding data representing a shopping list
How to create a simple array in PHP
In PHP, we would create this array using the built-in PHP array() function as follows:
$shoppingList = array(
"potatos",
"tomatoes",
"2% milk",
"prune butter",
"organic muesli",
"eggs",
"unsalted butter",
"half-sour pickles",
"shallots",
"bananas"
);
Notice that we never have to explicitly state what the key for each row is. If we don’t specify the key, it is automatically filled in with a number. The first element always has key 0, the second has the key number 1, the third has a key of 3, etc.
So the eighth element in the list, “half-sour pickles”, is automatically assigned a key with the number 7, and so on.
Accessing the elements of an array in PHP
If we wanted to echo the value of the 8th element in the list, we could use the following PHP command:
echo $shoppingList[7];
This would output the text “half-sour pickles”.
If we wanted to add another element containing the word, “hand soap”, to the end of the existing list of elements in the 11th position, we could use the following PHP code:
$shoppingList[10] = “hand soap”;
Alternatively, the following code will also add an element to the end of the existing list of elements in the array:
$shoppingList[] = “hand soap”;
The advantage of this latter code is that it does not require us to hard-code the number to use as the key for the new element in the array. This makes it a more reusable and flexible technique for adding an element to the end of an array.
Assigning custom keys
Alternatively, we could have explicitly specified the keys we wanted to use for each element in the array by using code like this:
$shoppingList = array(
9 => "potatos",
1 => "tomatoes",
2 => "2% milk",
8 => "prune butter",
3 => "organic muesli",
7 => "eggs",
4 => "unsalted butter",
6 => "half-sour pickles",
5 => "shallots",
0 => "bananas"
);
In this example, we have overriden the default automatically incrementing key numbering system and are specifying keys in whatever order we like.
Associative arrays
In fact, if we wanted to, we could use strings for keys instead of integers. This is done in more or less the same was as we just saw used for assigning custom keys to an array.
For example, let’s say we wanted to create an array that held the grades of the students in a class. We could link up a student’s first name and grade as outlined in this diagram:

An associative array
How to create an associative array in PHP
To create an associative array in PHP, based on the diagram above, we would use the following code:
$grades = array(
"Amos" => "A",
"Jack" => "A",
"Susan" => "B",
"Donny" => "C",
"Michael" => "C",
"Joshua" => "F"
);
Accessing the elements of an associative array in PHP
If we wanted to echo the grade for Susan, we could use the following code:
echo $grades["Susan"];
If we wanted to add a new element to this array to hold Luis’s grade, a B+, we could used the following code:
$grades["Luis"] = "B+";
Debugging arrays in PHP
If you are working with arrays in PHP and are having problems, it often helps to output the contents of the array using the built-in print_r() function of PHP.
For example, to output the array containing grades that we created above, we could use the following code:
print_r($grades);
Running this code will output the following text to the browser:
Array
(
[Amos] => A
[Jack] => A
[Susan] => B
[Donny] => C
[Michael] => C
[Joshua] => F
[Luis] => B+
)
This will allow us to easily see the values that are stored inside the array. And we can use this information to check to see if the values we intended to store in the array are indeed being stored there properly.
Multidimensional arrays
Let’s now imagine that we wanted to store a list of data that had more than just a key and a value. For example, let’s say we had a list of our favorite classical symphonies, structured as a sort of table of data:

A multidimensional array
This has more than just one value associated with each key. In this case, each key has a list of data associated with it, including “title”, “composer”, “key” and “year” values. In other words, there is a sub-array of data associated with each key.
How to create a multidimensional array in PHP
So, in order to create such a multidimensional array of data, we create an array filled with arrays:
$symphonies = array(
array(
"title" => "Symphony #1",
"composer" => "Jean Sibelius",
"key" => "E minor",
"year" => "1898"
),
array(
"title" => "Symphony in C major",
"composer" => "Richard Wagner",
"key" => "C major",
"year" => "1832"
),
array(
"title" => "Symphony #7",
"composer" => "Ludwig van Beethoven",
"key" => "A major",
"year" => "1811"
),
array(
"title" => "Symphony #3",
"composer" => "Anton Bruckner",
"key" => "D minor",
"year" => "1873"
),
array(
"title" => "Symphony #10",
"composer" => "Dmitri Shostakovich",
"key" => "E minor",
"year" => "1953"
),
array(
"title" => "Symphony #9",
"composer" => "Antonin Dvořák",
"key" => "E minor",
"year" => "1893"
)
);
In many ways, this array is not so different from the simple shopping list array we created at the beginning of this tutorial. We have not specified what keys to use for each element in the array, so PHP automatically assigns incrementing integers as the keys.
It just so happens that each element in the list is an array, rather than some text or a number. That’s why it is called a multidimensional array.
Accessing the elements of an associative array in PHP
To read the values contained within the array, we must bear in mind that we have two arrays. In our example above of the symphonies, the outer array is a simple array whose keys are integers. The inner arrays are associative arrays with strings as keys.
To print out the contents of the “composer” field of the third element in the array of symphonies, we could use the following code:
echo $symphonies[2]["composer"];
This would output the text:
Ludwig van Beethoven
And if we wanted to add a new symphony to the list, we could use code like the following:
$symphonies[] = array(
"title" => "Symphony #3",
"composer" => "Gustav Mahler",
"key" => "D minor",
"year" => "1893"
);
Notice that we are not specifying the key for this new element of the array, so PHP automatically assigns it the next available integer, in this case 6.
Looping through simple arrays
Often, in programming, we want to loop through the elements in an array. The built-in foreach() function in PHP is very useful for this purpose.
To loop through a simple array, such as the shopping list array we created at the beginning of this tutorial, we can use the foreach loop in the following code. This will output the value of each element in the array:
foreach ($shoppingList as $item) {
echo $item . "<br />";
}
Looping through associative arrays
When you have an associative array, as in the student grades example above, you will often be interested not only in the value of each element of the array, but also in its custom key. To access both the key and the value of each element as you loop through the array, you can use a foreach loop like the following:
foreach ($grades as $name => $grade) {
echo $name . " got a " . $grade . "<br />";
}
This effectively goes through each element in the $grades array one at a time, and divides it up into two variables: $name and $grade. $name holds the key, and $grade holds the value. This loop iterates through each element in the array, and results in the outputting of the following text:
Amos gets a A<br />
Jack gets a A<br />
Susan gets a B<br />
Donny gets a C<br />
...
… and so on.
Looping through multidimensional arrays
When dealing with multidimensional arrays, as we have seen, it is often the case that you have a list of associative arrays within a simple array.
When this is the case, such as with the array of symphonies in the examples above, we can use the following code to loop through and output contents of the multidimensional array:
foreach ($symphonies as $symphony) {
echo $symphony["composer"] . " composed " . $symphony["title"] . " in " . $symphony["year"] . "<br />";
}
This code iterates through each element in the $symphonies multidimensional array, and puts the value of each element into a variable called $symphony. Recall that each element of the $symphonies array is actually an array in its own right. So for each iteration of the loop, the $symphony variable holds an associative array containing just the data for that particular symphony.
We can then access the values held within this $symphony array the same way we access values held within any associative array: by using the proper keys. The end result is the output of text like this:
Jean Sibelius composed Symphony #1 in 1898<br />
Richard Wagner composed Symphony in C major in 1832<br />
Ludwig van Beethoven composed Symphony #7 in 1811<br />
This technique of looping through multidimensional arrays will come in handy when we begin to deal with databases.
October 31st, 2009 §
Your in-class assignment today is to update your e-commerce pages from the previous class to be more “dynamic” and “templatized”.
Templatize the common sections of all pages in the entire site
Use separate PHP include files for the top ad banner, global navigation, breadcrumbs, skyscraper ad, and footer. On a real site, these sections would be the more-or-less the same on all pages, so you would want to have them stored in reusable files. These files will be included into the main XHTML file for each page using the include() function of PHP. Feel free to check out the include examples that are up on the server.
Note: As a convention in this class, whenever you create a file that has a snippet of XHTML that is included into another page but never displayed directly on its own, I would like you to give it a name prefixed with the “_” character. For example, the include files used in this assignment could be called:
- _header.php
- _breadcrumbs.php
- _ad_banner.php
- _ad_skyscraper.php
- _footer.php
Templatizing these parts of the page will allow you to reuse those sections on multiple pages on your site, if you ever build it out to be more than one page, without having to rewrite the code for each. Naming the files with this convention will make it obvious when looking at a list of your own files which ones are main XHTML pages and which ones are meant to be include files.
Templatize the products
Once you have finished that, it’s time to start templatizing the actual products that are displayed on the page as well. This would, in theory, allow you to use the same page template for multiple categories of products.
We will do this in a different way than how we templatized the repeating sections of the page. We will be using multidimensional arrays this time. This exercise will be useful as a preparation for when we start to store data in databases.
Eventually, we will want the data for the products to be pulled from a database. But for now, we’re just going to store data in an array as an intermediary step to that goal.
To templatize the products, create a PHP multidimensional array that contains all of your product data. And use a PHP foreach loop to loop through that array and display the product data for each product on your page, rather than having it all hard-coded in the XHTML.
Do the tutorials, understand the examples
You are going to have to go through all the PHP tutorials on the Tizag site and my introduction to arrays in order to get a grasp of arrays and multidimensional arrays in particular.
Here is an example of how to get starting using a multidimensional array for this assignment. I did not show how to use the foreach loop here, so you will have to investigate that, based on the example of looping through an array using the foreach command shown here.
Be sure to keep a backup of the work you did on the e-commerce page in previous classes – do not overwrite it, just make a copy of it.
Links to helpful documentation