Week 6: More Interactive Data Processing
Let's Start With Some Data For Class Tonight (grab it in this file here) and
build a form to connect to our writefile.php page.
Providing A Form For Data Submission
We can create a simple form for our intended Web audience to submit more data:
Note: We should take care to name our form fields something that describes the data being submitted well.
Writing a File
The fwrite() function is used to write a single line to a file. We can use it to store our data in a file.
Note: After a call to the fwrite() function the file pointer has moved on to the next line.
The example below reads a file line by line, until the end of file is reached:
Try it by filling out the form above.
$outfile = "updated.txt";
$data = array();
$row = 0;
$infile = fopen("data.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
$handle = fopen($outfile, 'w');
$next = fgets($infile);
$town = substr($next,0,strpos($next,","));
$pollen = substr($next,strpos($next,",")+1,strpos($next,";")-strpos($next,",")-1);
$uv = substr($next,strpos($next,";")+1);
$data[$row++] = array($town, $pollen, $uv);
//dump the array of data read
//write the new data
echo "<br /><br />I wrote: ".$_POST['town'].",".$_POST['pollen'].";".$_POST['uv']."\n";
Passing Parameters Between Forms and Responses with URL Processing
PHP provides the pieces to build a mod_rewrite function (presented below in its entirety) that lets you parse data input into the $_GET, $_REQUEST, and $HTTP_GET_VARS global variables without having to use the standard CGI syntax.
$request - the string variable you need parsed into the global namespace so it is available to your processing code
$array_delim - the array pair value delimiter
$pair_delim - the delimiter that separates pair names from pairs values
mod_rewrite returns: void or no return value;
Example mod_rewrite usage:
The standard CGI link url would be: http://yoursite.com/somepage.php?id=20&name=funny. You want your url to be: http://yoursite.com/somepage/id-20/name-funny.html
Create a PHP document named somepage.php and you put the following PHP code at the top of your page:
$request = $_GET['rewrite'];
mod_rewrite( $request, '/', '-' );
# if you have register_globals enabled on your PHP engine, uncomment the following:
# extract( $_GET, EXTR_OVERWRITE );
What happens when a user clicks the link:
1. The user's browser sends request for "somepage/id-20/name-funny.html"
2. The ModRewrite Engine is on and request matches pattern matches "somepage/"
3. ModRewrite engine changes the request to somepage.php?rewrite=id-20/name-funny
4. The PHP engine is called and the script is run, the $_GET['rewrite'] is processed by the mod_rewrite function,and the mod_rewrite function changes this value id-20/name-funny into
$_GET['id'] = '20';
$_GET['name'] = 'funny';
...then if you depend on register_globals being on ( because you are converting an old script )
you call this:
extract( $_GET, EXTR_OVERWRITE );
right after the mod_rewrite function to put all the new $_GET variables into the global name space to make it available to your processing page.
Take a look at the mod_rewrite function and think about how it works given your learning in class to this point. We'll go over it together in class in more detail.
function mod_rewrite( $request, $array_delim, $pair_delim )
global $_GET, $HTTP_GET_VARS, $_REQUEST;
$value_pairs = explode( $array_delim, $request );
$make_global = array();
foreach( $value_pairs as $pair )
$pair = explode( $pair_delim, $pair );
$_GET[$pair] = $pair;
$_REQUEST[$pair] = $pair;
$HTTP_GET_VARS[$pair] = $pair;
For more information on the server-side rewrite ability, see this article.
Review of Hidden Form Fields
Hidden is an input type attribute value available to HTML forms. When you add a type=hidden attribute-value pair to an INPUT element, the hidden field is used to send information from browser to the server without your Web-based audience having to input it anywhere in the system. Typically this is used to send some logical data that has nothing to do with user but used at the server in PHP program logic. For example state, action, or passing the result of another module, etc. As an example:
<textarea rows=3 cols=60>
<input type="hidden" name="action" value="step2">
and the value of this field can be accessed in PHP by following:
<textarea rows=3 cols=60>
echo "The value of the action parameter value is:".$_POST['action'];
which prints out a step2 string as the action parameter value.
Overview of Cookies
A cookie is often used to identify a user to your code.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the
server embeds on the user's computer. Each time the same computer requests a
page with a browser, it will send the cookie too. With PHP, you can both create
and retrieve cookie values.
How to Create a Cookie?
The setcookie() function is used to set a cookie.
Note: The setcookie() function must appear BEFORE the <html> tag.
setcookie(name, value, expire, path, domain);
In the example below, we will create a cookie named "user" and assign the
value "Alex Porter" to it. We also specify that the cookie should expire after
setcookie('user', "Alex Porter", time()+3600);
Note: The value of the cookie is automatically URLencoded when
sending the cookie, and automatically decoded when received (to prevent
URLencoding, use setrawcookie() instead).
You can also set the expiration time of the cookie in another way. It may be
easier than using seconds.
setcookie('user', "Alex Porter", $expire);
In the example above the expiration time is set to a month (60 sec * 60
min * 24 hours * 30 days).
How to Retrieve a Cookie Value?
The PHP $_COOKIE variable is used to
retrieve a cookie value.
In the example below, we retrieve the value of the cookie named "user" and
display it on a page:
// Print a cookie
// A way to view all cookies
In the following example we use the isset() function to find out if a cookie
has been set:
echo "Welcome " . $_COOKIE['user'] . "!<br />";
echo "Welcome guest!<br />";
How to Delete a Cookie?
When deleting a cookie you should assure that the expiration date is in the
// set the expiration date to one hour ago
setcookie('user', "", time()-3600);
What if a Browser Does NOT Support Cookies?
If your application deals with browsers that do not support cookies, you will
have to use other methods to pass information from one page to another in your
application. One method is to pass the data through forms (forms and user input are described
earlier in this tutorial).
The form below passes the user input to "welcome.php" when the user clicks on
the "Submit" button:
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
Retrieve the values in the "welcome.php" file like this:
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
Overview of Session Management
In Web applications, it is frequently desirable to remember if a user has visited a site previously, remember the sequence of pages visited during a session, and associate information with a specific user's session.
You can manage a session like e-commerce sites manage a shopping basket.
To accomplish these things, you can also see O'Reilly's page on the subject.