Posted: November 23rd, 2009 | Author: amos | Filed under: php | Tags: class 9 | No Comments »
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
Posted: November 23rd, 2009 | Author: amos | Filed under: mysql, php | Tags: class 9, injection attack, sanitizing | 1 Comment »
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.
Posted: November 7th, 2009 | Author: amos | Filed under: assignments, mysql | Tags: class 8 | No Comments »
If you have finished the in-class assignment of creating a message board, you are ready for the advanced assignment.
The advanced assignment is to add the ability for users to upload images along with their message posts.
add_post.php
So when users add new posts, they enter in their name, the title of the post, the body of the post, as well as the image that goes along with the post.
Here’s the updated wireframe for the add_post.php page:

updated add_post.php wireframe
You will want to check out the upload file example on the server here.
You use an <input type=”file” …> tag to allow users to select a file to upload.
Make sure your form has the “enctype” attribute set to “multipart/form-data”. This indicates to the server that it should expect to be receiving binary data for the file.
process_post.php
When the server receives the data that the user submits along with the HTTP POST request for process_post.php, it has to store the data in the database, as you have already done in the first part of this assignment.
You will want to create a new “image_path” field in your messages table in the database where you will store the path where you uploaded the image. You can get the path where the image is uploaded by going through the file upload example code linked above.
So when you create the new row in the database table, you will be storing the author, post title, image path, and post body in the database table.
index.php
And when a user views the list of all the messages, if there is an image that has been uploaded along with a particular message, that image shows up next to the message. If there is no image associated with a post, the layout should adjust accordingly.
Here is the updated index.php wireframe:

updated index.php wireframe
Very advanced assignment
If this was too easy for you, here is a very advanced assignment. Require the users to register with your site before they can post a message.
Users should be able to view the home page whether they are registered or not.
But only registered users should be able to post a new message. If a user has not registered, they should be redirected to the index.php page if they try to view the add_post.php or process_post.php pages.
Posted: November 7th, 2009 | Author: amos | Filed under: assignments, mysql | Tags: class 8 | No Comments »
Your assignment this class is to create a message board. The message board allows users to view all of the messages that have been posted to the board so far. It also allows users to post new messages.
Here is the user flow of the site:

User flow of message board site
index.php – the message list page
When the user first comes to the site, they see the main page, index.php. This page shows them a list of all of the messages on the board in reverse chronological order. The page reads all of the rows of data from the database table and displays them.
This page also has a link to “add a new post”. When the user clicks that link, she is brought to add_post.php.

index.php wireframe
You will want to use code similar to what is available in the read.php example available on the server here.
Also, you will eventually want to format the dates that you retrieve from the created field of the database table, you will want to read this post about beautifying MySQL timestamps.
add_post.php – the post page
add_post.php consists of a form the user can fill out in order to post a new message. This form has three fields: the user’s name, the post title, and the post body. When the user clicks submit, this page makes an HTTP GET request for process_post.php, and passes along the data that the user entered into the form as part of the query string of the URL of the request.

add_post.php wireframe
This page can be a simple XHTML page. It’s ok to name it add_post.php even if it just has XHTML code inside of it.
process_post.php – the process post page
The process_post.php script receives the data that was passed in the GET request to the server by using the built-in PHP $_GET or $_REQUEST variables, and enters that information as a new row in the database table.
You will want to use code that is similar to the PHP used in the create.php example available on the server here.
This script will then redirect the user back to the main page, index.php. Check out this example of how to redirect a user from one page to another. You will be using the built-in header() function in PHP in order to pass a special “Location” HTTP header from the server to the client that instructs it to go make a request for a different page.
For example, this code redirects a user to the nytimes.com website:
header("Location: nytimes.com"); //redirect to another page
Posted: November 7th, 2009 | Author: amos | Filed under: mysql | Tags: class 8, create, crud, delete, read, update | 1 Comment »
Create
INSERT INTO abloomberg_animals (name, color) VALUE (‘zubr’, ‘brown’)
Read
SELECT * FROM abloomberg_animals WHERE 1
SELECT name, color FROM abloomberg_animals WHERE id=15
Update
UPDATE abloomberg_animals SET name=’zubr’ WHERE id=15
UPDATE abloomberg_animals SET name=’zubr’, color=’brown’ WHERE id=15
Delete
DELETE from abloomberg_animals WHERE id=15
Posted: November 6th, 2009 | Author: amos | Filed under: mysql | Tags: class 9 | No Comments »
Let’s cover the details of the SELECT statement in SQL. The SELECT statement is the command we use to do the Read part of database CRUD. CRUD is an acronym that stands for Create, Read, Update, Delete – the four operations you are most likely to do with a database. At any given time, you are either creating data, reading data, updating data, or deleting data.
We’ll start with the simplest possible SELECT statement in action, and then move to more nuanced implementations.
Let’s say we run a business managing art collections for wealthy individuals. We might want to build an inventory management application to keep track of which paintings our clients own.
The first step towards that would be to have a table that holds a list of our clients. Let’s call this table “collectors”. And let’s say we put the following information in it:

collectors table
An easy read
To do a query on the database to get all the information on all the rows in our table, we might do a simple SELECT statement as follows:
SELECT * FROM collectors WHERE 1
And reacall that in PHP, we execute queries on the database using the mysql_query() built-in function:
$myQuery = "SELECT * FROM collectors WHERE 1";
$result = mysql_query($myQuery);
This would return the full data set internally represented in basically the same way as what we’ve already seen. The order that the data is stored inside of a database is not necessarily chronological order, so the data may show up in a different order if you don’t specify in what order you’d like to receive it.

result set of full select query
Selecting specific fields
Let’s hypothetically say we only wanted to get the id and last name for each collector in our table. To do this, we would specify which fields we were interested in as follows:
SELECT id, last_name FROM collectors WHERE 1
Notice that we use a comma delimited list of field names after the SELECT keyword. This query would return a data set that looked like this:

A result set with only two fields
Ordering results
And now let’s say we wanted to order the results alphabetically by last name starting with A and ending in Z:
SELECT id, last_name FROM collectors WHERE 1 ORDER BY last_name ASC
The “ORDER BY” clause takes two parameters: the field we want to order the results by, and the order we want them returned in: either ASC or DESC for ascending and desc ending respectively.
Our example query would return a result set that looked like this:

result set ordered by the last_name field
Modifying the WHERE clause
To do a query that only returned the results for the collector with id #3, we would do a query like this:
SELECT * FROM collectors WHERE id=3
This would return a data set that looked like this:

result set matching only a single row
We can specify any criteria we want in the WHERE clause. If we only wanted to get the data for users who were NOT id #3, we could do this:
SELECT * FROM collectors WHERE id<>3
The <> symbol is the SQL way of saying NOT EQUALS.
Paginating results
Lastly, but not leastly in this set of examples, let’s say we had 400 collectors in our table. And we want to make a web-based interface that only shows 10 at a time, ordered alphabetically by last name. Will will have page number links so users can click on which “page” of results they want to view: 1,2,3,4, etc.
To paginate results, we would require a LIMIT clause on the SELECT query. For example, this query would return only the first 10 rows:
SELECT * FROM collectors WHERE 1 ORDER BY last_name ASC LIMIT 0,10
The LIMIT clause in this case takes two arguments, separated by a comma: the result number to start from, and the number of results to return. In this case, we are telling SQL to start from the first result in the entire data set of results, and return only 10 results total.
To get the next “page” of results, we might make a query to start from the 11th result, and return the next 10:
SELECT * FROM collectors WHERE 1 ORDER BY last_name ASC LIMIT 11,10
And so on…
Joining multiple tables of data
Now that we’ve covered all the basic elements of the SELECT statement, let’s use them to select data from multiple tables.
Let’s say we had a second table in our example. This table was a list of all the paintings that each of our collectors owns. Let’s call this table “paintings”, and it might look like this:

paintings table
Notice that this table has a foreign key field, “collector_id” that holds the id of the collector who owns each particular piece.
So let’s now say we wanted to combine the two sets of data. We want to get a list of all the paintings in our database, as well as the last names of collectors who own them. We might do a query like this:
SELECT paintings.*, collectors.last_name FROM paintings, collectors WHERE paintings.collector_id=collectors.id
This would return a set of data that looked like this:

esult set with data from two tables
Notice that we have merged data from both tables. The result set now has all of the data from the “paintings table”, as well as the last_name field from the “collectors” table.
There are two new things going on in this example. Firstly, when we are dealing with multiple tables, we have to be very clear about which fields we want to get data from, and which table those fields are in.
In this case, we asked for all fields from the “paintings” table by specifying “paintings.*”, and we also asked for only the “last_name” field of the “collectors” table by specifying “collectors.last_name” in the query.
Secondly, the WHERE clause tells SQL how to merge the tables. By specyfing “WHERE paintings.collector_id=collectors.id”, we are telling SQL to match up the two sets of data by the fields “paintings.collector_id” and “collectors.id”. In other words, we are telling SQL that the “collector_id” field in the “paintings” table is a foreign key that points to the “id” field of the “collectors” table.
So for every row in the “paintings” table, SQL looks at the “collector_id” field, and finds the “last_name” field from the corresponding row in the “collectors” table.
This type of merging of data from two tables by matching up a field in one table with another field from another table is known as an inner join in SQL terminology. This is, by far, the most common type of join, or merge, that developers do. But there are also left joins, right joins, and outer joins… you can research those if you’re brave.
Posted: November 6th, 2009 | Author: amos | Filed under: mysql | Tags: class 8 | No Comments »
Tables of data
Relational databases treat data in the same grid-like way as an Excel spreadsheet. There are rows and columns of data. But databases have extra features that make them easier and more intuitive to work with.
Databases, tables, rows, and columns
Each relational database can hold multiple tables. Tables are the spreadsheet-like grids of rows and columns of data. So if you are familiar with Microsoft Excel documents. you can think of the database as the Excel document, and the tables as the individual sheets within that document.
Databases are faster
With plain text files, As the amount of data stored grows, so too does the amount of time it takes for the server to open the text file and go line-by-line through it. After only several hundred lines of data, there will be a noticeable lag when reading data from a text file. The same problems exist for writing, updating, and deleting data – the more data you have, the more time-consuming those operations get, and other complications crop up.
Databases are optimized to quickly do the most common tasks with data: Creating new data in storage, Reading data from storage, Updating data, and Deleting data. These tasks, called CRUD for short, are exactly what databases like MySQL are designed to do quickly and efficiently. A database server can loop through thousands of rows of data in a tiny fraction of a second.
The database uses indexes to pre-sort data in a variety of ways to make it faster to sort through when you eventually request data from it.
Databases respond to queries
Databases also allow you to pinpoint individual pieces of data relatively quickly. At a high level, you can make a request to the database to return particular rows and columns of data you want to access (whether it be for creating, reading, updating or deleting), and the database will automatically find that data and return it without you having to loop through the other rows and columns manually.
Of course it gets complicated, like everything else, but the idea is straightforward. You make a request for data, and the server responds. A request like this for a particular set of data is called a “query”, and SQL is the language we will use to make queries.
A typical SQL query to request the contents of all the rows out of a table called “users” would look something like this:
SELECT * FROM users
We’ll get into the details of SQL syntax later.
Relationships between tables
Data in one table is often related to data in other tables. This can be most easily explained through an example.
Let’s say, hypothetically, that we’re building a site where users can upload photos to a blog. The first step would be to have a ‘users’ table that stores just the basic information about each user. It might looks something like this:

users table
Notice that there is an “id” field. So each row, meaning each entry in this table, has a unique identifier. Each table must have a unique identifier, known in database parlance as the primary key.
So if I were to ask a question, such as “what is the username of user #3?”, it would be possible, in code, to write a SQL query that answers this question. The code would look for the “username” field of the row in the “users” table with id=3, and that query would return the answer. That query might look something like this:
SELECT username FROM users WHERE id=3
In order to keep track of which images have been uploaded by which users, we might create another table called “images”. This table would have the details of each image which has been uploaded, including which user uploaded it. The “images” table might be set up as follows:

images table
Again, we see that there is an “id” field, which is the primary key for the “images” table, just like we had an “id” field in the “users” table. Each table will have an “id” field that serves as the primary key for that table.
But notice that the “images” table also has a field called “user_id”, which would be used indicate the primary key of the user who uploaded the image in each row. So when we, in our code, create a new row in the “images” table, we would tell the database what data to put in each of the fields; and in the “user_id” field, we would tell it to put in the unique identifier of the particular user who uploaded that image in that field.
Then, if we were, in code, to read the data out of the “images” table, we be able to see that user #1 uploaded photo #2, and user #3 uploaded photo #3, for example.
This “user_id” field in this case is called a foreign key. The term, foreign key, just means that we are using the primary key of one table (in this case, the “users” table) as a piece of data in another table (in this case, the “images” table). That is how we conceptually link the data between two tables.
It’s important to note that the relationship between the “id” field of the “users” table and the “user_id” field of the “images” table is not something that is automatically managed and handled by MySQL. Some database servers do have a special feature where the database automatically “knows” about this relationship. But the MySQL server we are using is ignorant of this relationship, so we have to make sure our code is smart enough to know what data is related to what other data – it’s not built into the database.
Posted: November 6th, 2009 | Author: amos | Filed under: php, xhtml | Tags: class 8 | 1 Comment »
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.
Posted: November 1st, 2009 | Author: amos | Filed under: php | Tags: arrays, class 7, multidimensional | No Comments »
To complete the templatizing assignment, 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.