Dynamic Web Content with PHP

This material from November 4th's lecture attempts to help you continue gaining comfort with creating interactive processes for passing data back and forth from your Web server and your intended audience (or serendipidous audience if you aren't targeting one). Data processing services need not use forms for data sharing. Any data that can be passed between forms can also be passed behind the scenes using other interactive session features built into the PHP language.

Lecture 8: More Interactive Data Processing

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 $_GET, $_REQUEST, and $HTTP_GET_VARS global variables. If your script relies on register_globals being enabled call extract( $_GET, EXTR_OVERWRITE ); after using this function to register again the $_GET array pair values into the global namespace.

mod_rewrite inputs:

$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:


Your original link url was: http://yoursite.com/somepage.php?id=20&name=funny. You change your url to: http://yoursite.com/somepage/id-20/name-funny.html In the script somepage.php and you put the following PHP code at the top of your page:
if( $_GET['rewrite'])
{
$request = $_GET['rewrite'];
mod_rewrite( $request, '/', '-' );

# if you have register_globals enabled, uncomment the following
# extract( $_GET, EXTR_OVERWRITE );
}

What happenes 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[0]] = $pair[1];
$_REQUEST[$pair[0]] = $pair[1];
$HTTP_GET_VARS[$pair[0]] = $pair[1];
}
}

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">
</textarea>

and the value of this field can be accessed in PHP by following:

<textarea rows=3 cols=60>
<?php
echo "The value of the action parameter value is:".$_POST['action'];
?>

</textarea>

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.

Syntax

setcookie(name, value, expire, path, domain);

Example 1

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 one hour:

<?php 
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
.....

Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

Example 2

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

<?php
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
?>
<html>
.....

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:

<?php
// Print a cookie
echo $_COOKIE["user"];
// A way to view all cookies
print_r($_COOKIE);
?>

In the following example we use the isset() function to find out if a cookie has been set:

<html>
<body>
<?php
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
  echo "Welcome guest!<br />";
?>
</body>
</html>


How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

<?php 
// 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:

<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />

Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>

</html>

Retrieve the values in the "welcome.php" file like this:

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />

You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>

Overview of Session Management

Another good overview is here.

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, youneed to have “stateful” connections between client and server: That is, association information (state) with the connection.

HTTP was originally designed to not be stateful, leading to the addition of the Cookie mechanism. But, there are some problems with cookies:

  • Browsers can refuse to accept cookies.
  • Cookies add network overhead to send lots of information back and forth.
  • There are also limits to the amount of information that can be sent.
  • Some information you just don't want to save on the client's computer.

PHP Sessions provide an alternate solution that eliminates some of the issues: store session information on the server, and have the client only store an identifier for its information as stored on the server.

The identifier is known as a session ID. The session ID is stored using a cookie (can be passed as a GET parameter as well).

The server then uses the session ID to retrieve the information it has stored on the server.

Session information is typically stored in files on the server, though options exist for using shared memory, and also writing your own handlers (e.g., to use a database for storage).

Setting and Retrieving Session Variables

To start a session, call session_start() to create a session identifier. The session identifier is passed between client and server either as a Cookie, or in GET parameters.

Then, you can create, access, and modify session variables:

  • $_SESSION[session_var_name] = value; ($_SESSION is only available once you call session_start())
  • $local_variable = $_SESSION[session_var_name];

You can check if session variable is set by using isset().

To end a session, call session_destroy().

Security of Session Data - In general, you cannot guarantee that session data will remain private as often, the session data files can be read by any Web application on the same server. The session ID can be grabbed by looking at the GET parameters (for GET-based passing of the session ID), or by eavesdropping the on-the-wire protocol (to get the cookie with the session ID). If the session holds a password, someone can then "replay" the session ID back to the server. Cookie data, though stored on the client side, are sent across the wire in-the-clear as text that can be easily understood. Client machines might be compromised, such as by malicious software inadvertently downloaded, or by a virus.