9. Increasing Functionality

What We Will Cover


Elucidations

Homework Questions?

Quiz Questions?

Questions from last class?

9.1. Functions

Objectives

At the end of the lesson the student will be able to:

  • Write code to pass values to functions
  • Write code to return a value from a function
  • Describe identifier scope
  • Code their own functions

9.1.1: About Functions

Function -- a subprogram (method, procedure or subroutine) that executes a block of code when called.

Why Functions?

  • Programs can call functions at need, allowing repeated use of the function
  • Aids in structuring code
  • Makes program development more manageable
  • Makes it easier to reuse sections of code

Using Functions

  • Functions are invoked by a function call
  • Arguments are used to send information to functions
  • Functions return a result to the calling function (caller)
  • Similar to a boss (caller) asking a worker (called function) to complete a task

Example Function Calls

    print("Hello");      // no return value
    $value = pow(2, 3);  // value gets int 8
    print($value);
    $num = -2.0;
    $value = abs($num);  // value gets float 2.0
    print($value);
    

9.1.2: Predefined Functions

  • PHP offers a multitude of libraries containing predefined functions
  • For a complete list: Function Reference
  • Some of those commonly used for Web applications are listed below
  • Some database function libraries are listed as well
  • We have discussed some of the libraries and will discuss more during the course
  • You should always use predefined functions when they are available

Some Commonly-Used Function Libraries

Library Description
Arrays For interacting with and manipulating arrays.
BC Math For arbitrary precision mathematics with numbers of any size and precision represented as strings.
Date/Time For getting the date and time from the server.
Java For interacting with Java on the server.
Mail For sending email.
Math For mathematical operations not provided by operators (see lesson 6.2.6).
Misc. For functions that do not fit into other categories such as die(), eval(), highlight_file() and sleep().
Output Control For controlling when output is sent from the script.
PHP Options/Info For getting information about PHP itself.
Program Execution For executing commands on the operating system of the server.
Pspell For checking the spelling of a word and offering suggestions.
PCRE For using Perl-compatible regular expressions.
Regexps For using POSIX extended regular expressions.
Session For saving some data across multiple page accesses.
Strings For manipulating strings (see lesson 7.1).
URLs For dealing with URL strings.
Variables For testing and manipulating variables.
Zip For reading ZIP compressed archives and the files inside them.
Zlib For reading and writing gzip (.gz) compressed files.

Some DataBase Function Libraries

Library Description
dba For accessing Berkeley DB style databases.
dBase For accessing records stored in dBase-format (dbf) databases.
dbx A database abstraction layer for accessing all supported databases using a single calling convention.
COM For accessing COM objects on Windows platforms, including MS Access databases.
FrontBase For accessing FrontBase database servers.
filePro For read-only access to data stored in filePro databases.
Informix For accessing Informix (IDS) 7.x, SE 7.x, Universal Server (IUS) 9.x and IDS 2000.
Firebird/InterBase For accessing InterBase databases put out by Borland/Inprise.
Ingres For accessing Ingres II database servers.
MS SQL Server For accessing MS SQL Server databases.
mSQL For accessing mSQL database servers.
MySQL For accessing MySQL database servers.
MySQLi For accessing MySQL database servers version 4.1 and above.
OCI8 For accessing Oracle8 and Oracle7 databases using the Oracle8 Call-Interface (OCI8).
ODBC For accessing database for which you have ODBC driver.
Ovrimos For accessing Ovrimos SQL Server databases.
PostgreSQL For accessing PostgreSQL database servers.
SQLite For accessing the SQLite Embeddable SQL Database Engine.
Sybase For accessing Sybase database servers.

9.1.3: Writing Functions

  • Programmers can write customized functions
  • Syntax:
  • function functionName(parameterList) {
        ...
    }
    

For Example

  • What do you notice that is different about the following code?
  • <?php
    function printBold($text) {
        print(
    "<b>$text</b>");
    }

    print(
    "This line is not bold<br>\n");
    printBold("This line is bold");
    print(
    "<br>\nThis line is not bold");
    ?>

  • Displays the output:
  • This line is not bold
    This line is bold
    This line is not bold

How the Function Works

  • PHP ignores the function definition until it is called
  • When called, PHP jumps to the function definition
  • The argument "This line is bold" is copied to the parameter $text
  • Code executed by the function is enclosed in curly brackets {...}
  • Within the function the parameter is used like a variable
  • After the function is finished, PHP jumps back to the statement after the function call
  • Note that the parameter is no longer useable after the function is finished
  • Remember that function names are case-insensitive

Programming Style: Function Naming Conventions

  • Use verbs to name functions, since they perform an action
  • Start function names with a lower case letter

9.1.4: Returning a Value

Return Statement

  • Functions that return a value must execute a return statement
  • For example:
  • <?php
    function makeBold($text) {
        
    $text "<b>$text</b>";
        return 
    $text;
    }

    print(
    "This line is not bold<br>\n");
    $line makeBold("This line is bold");
    print(
    $line."<br>\n");
    print(
    makeBold("This line is bold too!"));
    print(
    "<br>\nThis line is not bold");
    ?>

  • Displays the output:
  • This line is not bold
    This line is bold
    This line is bold too!
    This line is not bold

Exiting Early

  • Sometimes you do not want to execute all the code in a function
  • You can use a return statement to stop execution and return from anywhere
  • Control returns immediately from a function when a return is executed
  • For example:
  • <?php
    print "max(1, 2) = ".max2nums(1,2)."<br>\n";
    print 
    "max(2, 3) = ".max2nums(2,3)."<br>\n";

    function 
    max2nums($num1$num2) {
        if (
    $num1 $num2) {
            return 
    $num1;
        } else {
            return 
    $num2;
        }
    }
    ?>

  • Displays the output:
  • max(1, 2) = 2
    max(2, 3) = 3

9.1.5: Scope

  • To avoid clashes between variables in different functions, PHP limits their scope
  • Variables declared inside a function only work within the function
  • When the function returns, the use of the variable is lost
    • The value of the variable is lost also
  • Consider the following code:

<?php
$num1 
1;
$num2 5;
changeValues($num1$num2);
print 
"<br>\nNew values: ".$num1.", ".$num2."<br>\n";

function 
changeValues($num1$num2) {
    print 
"Original values: ".$num1.", ".$num2;
    
$num1++;
    
$num2++;
    print 
"<br>\nChanged values: ".$num1.", ".$num2;
}
?>

  • Displays the output:
  • Original values: 1, 5
    Changed values: 2, 6
    New values: 1, 5

  • Variables changed inside the function have no effect on variables outside the function
  • Note that you can return multiple values using call by reference
  • changeValues(&$x, &$y);
  • However, call by reference is generally discouraged in PHP
    • PHP is optimized to use call by value

Using Global Variables

  • Variables declared outside of functions are global variables
  • Global variables are not automatically available inside of functions
  • To use global variables within a function, use the global keyword followed by the variable name
  • What is different about the following code?

<?php
$num1 
1;
$num2 5;
changeValues2();
print 
"<br>\nNew values: ".$num1.", ".$num2."<br>\n";

function 
changeValues2() {
    global 
$num1$num2;
    print 
"Original values: ".$num1.", ".$num2;
    
$num1++;
    
$num2++;
    print 
"<br>\nChanged values: ".$num1.", ".$num2;
}
?>

9.1.6: Default Arguments

  • PHP allows functions with default arguments
  • If the argument is omitted during the function call, the function uses default values instead
  • A default value is specified in function's parameter list
  • Only the rightmost parameters can have default values
function calcVolume($length, $width = 1, $height = 1)
  • Last 2 arguments have defaults
  • Possible function calls:
calcVolume(2, 4, 6); // all arguments supplied
calcVolume(3, 5);    // height defaulted to 1
calcVolume(7);       // width and height defaulted to 1

9.1.7: Summary

  • A function is a block of code that returns a value when called
  • Declare functions using the keyword function, a name and a list of parameters
  • function functionName($param1, $param2, ...) {
        ...
    }
    
  • Functions return a value using the return statement
  • return $value;
  • Variables declared inside a function can only be used within the function
  • When the function returns, the value of the variable is lost
  • Global variables are not automatically available inside of functions
  • To use global variables within a function, use the keyword global followed by the variable name

Exercise 9.1

In this exercise we explore writing a function and view the variables available from the server.

Background Information

PHP has a function named var_dump that prints information about a variable. This function is useful when debugging variables in a script. However, values do not always display well because a browser ignores text formating. HTML provides the <pre>...</pre> tag to preserve the formatting of the text and you can use this tag to improve the output of var_dump().

Specifications

  1. Write a PHP program named dump.php with a function named dump() that accepts a single parameter.
  2. Within the dump() function, write code to print <pre>...</pre> tags.
  3. Between the <pre>...</pre> tags call the var_dump() function.
  4. Add code to call your function using:
  5. dump($_SERVER);
  6. Submit your dump.php program as the answer to this exercise.

9.2: Managing the Date and Time

Objectives

At the end of the lesson the student will be able to:

  • Get the date and time from PHP
  • Work with UNIX timestamps
  • Convert between PHP and MySQL date formats

9.2.1: Using the date Function

  • The date function provides the date and time
  • It has two parameters, one of which is optional
  • string date(string format [, int timestamp])
  • The format string consists of one or more letters with special meaning
  • Letters of the format string are replaced with parts of the date and time
  • If no timestamp argument is provided, the current date and time is used
  • For example:
  • <?php
    print date("m/d/y")."<br>\n";
    print 
    date("l F jS, Y @h:i A");
    ?>

  • Displays the output:
  • 09/03/10
    Friday September 3rd, 2010 @12:46 AM

  • Characters not understood as format codes, like slash (/), are just printed
  • For a list of the format string letters see the PHP manual for: date

9.2.2: Working with Timestamps

  • The second parameter to the date function was a Unix timestamp
  • Most Unix systems store the current date and time as a 32-bit integer
  • Contains the number of seconds since 1/1/1970
  • Provides a compact way of storing a date and time
  • Could create a January 19, 2038 problem
    • However, timestamps do not have a fixed size
    • Most computer systems will have a larger int size by then
  • Windows versions of PHP can use timestamps as well

Making Timestamps

  • To convert a date and time to a timestamp, use mktime()
  • int mktime([int hour [, int minute [, int second [, int month [, int day [, int year [, int is_dst]]]]]]])

  • As the square brackets show, all the parameters are optional
  • For all those left out, the function uses the current time and date
  • For example:
  • <?php
    $format 
    "l F jS, Y @h:i A";
    print 
    mktime()."<br>\n";
    print 
    date($formatmktime())."<br>\n";
    $ts mktime(date("H") + 50);
    print 
    "Fifty hours from now: $ts<br>\n";
    print 
    date($format$ts)."<br>\n";
    ?>

  • Displays the output:
  • 1283500005
    Friday September 3rd, 2010 @12:46 AM
    Fifty hours from now: 1283680005
    Sunday September 5th, 2010 @02:46 AM

  • Note the order of the parameters: why did the function designer choose that order?

9.2.3: Using the getdate Function

  • Another useful function is getdate()
  • array getdate([int timestamp])
  • Returns an associative array with information about the timestamp
  • If no timestamp argument is provided, the current date and time is used
  • For example:
  • <?php
    $dateArray 
    getdate();
    print_r($dateArray);
    ?>

  • Displays the output:
  • Array
    (
        [seconds] => 45
        [minutes] => 46
        [hours] => 0
        [mday] => 3
        [wday] => 5
        [mon] => 9
        [year] => 2010
        [yday] => 245
        [weekday] => Friday
        [month] => September
        [0] => 1283500005
    )
    
  • Note that key [0] is the timestamp

9.2.4: Converting Between PHP and MySQL Date Formats

  • MySQL works with dates in a YYYY-MM-DD format
  • You will usually want to perform some date conversion
  • You can convert the dates using either MySQL or PHP
  • We discussed using MySQL in lesson 5.4.5: Formatting the Date and Time
  • For example, you can use the DATE_FORMAT function with a query:
  • SELECT DATE_FORMAT(dateColumn, '%m %d %Y')
    FROM tableName;
    
  • You can also retrieve a date and time column as a Unix timestamp
  • SELECT UNIX_TIMESTAMP(dateColumn)
    FROM tableName;
    
  • You can covert date and time formats using PHP as well
  • Two useful functions for this are strtotime() to strftime()
  • You can use strtotime() to convert a date-time string into a timestamp
  • int strtotime(string time [, int now])
  • Once you have a timestamp, use strftime() to change the format
  • string strftime(string format [, int timestamp])
  • For example:
  • <?php
    $date 
    "2004-11-13";
    $ts strtotime($date);
    if (
    $ts !== -1) {
        
    $formattedDate strftime("%m/%d/%y"$ts);
    }

    print 
    "The original date is: $date<br>\n";
    print 
    "The formatted date is: $formattedDate";
    ?>

  • Displays the output:
  • The original date is: 2004-11-13
    The formatted date is: 11/13/04

  • Note that strtotime() returns a -1 if it cannot convert the date-time string

Useful PHP Date and Time Conversion Functions

Function Description
strtotime() For converting a date-time string into a timestamp.
strftime() For formatting a timestamp in locale specific manner.

9.2.5: Date Calculations

  • Timestamps are the easiest ways to work with dates and times in PHP
  • For instance, to find the difference between two times, just subtract them
  • $diff = $timestamp2 - $timestamp1;
  • If you want the difference in minutes, you divide by 60
  • print "Elapsed minutes: ".$diff / 60;
  • Use a similar technique for hours or days
  • $diffHours = floor($diff / 3600);
    $diffDays = floor($diffHours / 24);
    
  • You can add dates using the same techniques
  • $fiveDays = 5 * 24 * 60 * 60;
    $timestamp = $timestamp + $fiveDays;
    
  • You can code your own date and time functions using these techniques
  • We will explore this in the next exercise

9.2.6: Summary

  • Use the date function to get the date and time from your server
  • print date("l F jS, Y @h:i A"); 
  • Another way to get the date and time is with the getdate function
    • Returns date and time information as an associative array
  • The easiest way to work with dates and times in PHP is to use timestamps
  • Timestamps are a count of the seconds since the start of January 1, 1970
  • To convert a date and time to a timestamp, use mktime
  • With timestamps, you can use arithmetic to calculate days
  • $fiveDays = 5 * 24 * 60 * 60;
    $timestamp = $timestamp + $fiveDays;
    
  • To convert date formats between PHP and MySQL, you can use either MySQL or PHP
  • In PHP, you can use strtotime() to convert a MySQL date into a timestamp
  • Once you have a timestamp, use strftime() to change the format
  • In MySQL, you use the DATE_FORMAT and UNIX_TIMESTAMP functions with your queries
  • SELECT DATE_FORMAT(dateColumn, '%m %d %Y')
    FROM tableName;
    
    SELECT UNIX_TIMESTAMP(dateColumn)
    FROM tableName;
    

Exercise 9.2

In this exercise we write a function that computes a date.

  1. Write a PHP program named tomorrow.php with a function named tomorrow() that accepts no parameters.
  2. Add code to the tomorrow() function that prints tomorrow's date.
  3. Submit your tomorrow.php file as the answer to this exercise

9.3: More PHP Functions

Objectives

At the end of the lesson the student will be able to:

  • Generate random numbers
  • Test a variables state
  • Test a variables data type
  • Conditionally redirecting a browser to another URI

9.3.1: Generating Random Numbers

  • Random numbers are a series of numbers whose order cannot be predicted
  • Many computational problems need to use random numbers
  • Hard to find truly random numbers, even in real life
    • Dice never perfect
    • Cards never shuffled completely randomly
    • Computers can only handle numbers within a finite range and limited precision
  • Best that can be done in most cases is generate psuedorandom numbers
    • Sufficiently random for the task at hand
  • rand([int min, int max]) is a PHP function that produces series of psuedorandom numbers
    • Can set the range with optional arguments
  • PHP versions before 4.2.0 require the use of srand([int seed]) to seed the random number generator

For Example

  • One use of random numbers is to generate random images on a page
  • <?php
    srand
    (mktime());
    $die1 rand(16);
    $die2 rand(16);
    echo 
    "<img src=\"dice/die$die1.gif\">";
    echo 
    "<img src=\"dice/die$die2.gif\">";
    ?>

9.3.2: Checking Variable States

  • PHP variables are usually declared when a value is first assigned
  • $var = "some value";
  • Normally, your can easily see when a value is assigned to a variables
  • However, some variables are assigned from outside the a PHP page
  • For example, when a form sends variables using GET or POST
  • In these cases, you may not know ahead of time which variables are created
  • If you try to use a variable that has not been declared, you will get a warning message
  • Notice: Undefined variable: ...
  • These types of messages are not appropriate in your web pages
  • To prevent the messages, you must test for the presence of such variables before using them

For Example

<?php
echo 'Before $var is declared:';

// Evaluates to true because $var is not set
if (empty($var)) {
   echo 
'<br>$var is either 0, empty, or not set';
}

// Evaluates as false because $var is set
if (isset($var)) {
   echo 
'<br>$var is set even though it is empty';
}

$var 0;
echo 
'<br>After $var is declared:';

// Evaluates to true because $var evaluates to false
if (empty($var)) {
   echo 
'<br>$var is either 0, empty, or not set';
}

// Evaluates as true because $var is set
if (isset($var)) {
   echo 
'<br>$var is set even though it is empty';
}

?>

  • Displays the output:
  • Before $var is declared:
    $var is either 0, empty, or not set
    After $var is declared:
    $var is either 0, empty, or not set
    $var is set even though it is empty

Further Information

9.3.3: Testing and Changing Variable Types

  • Recall that PHP variables do not require a type to be defined
  • In fact, PHP variables automatically change types as needed
  • Usually, you do not care about the type of a variable
  • However, if you do want to know, then PHP provides functions to test the current type
  • These functions are often used to verify correct user input

Commonly Used Type Checking Functions

Function Description
intval() For getting the integer value of a variable.
is_array() For testing if a variable is an array.
is_bool() For testing if a variable is an boolean.
is_float() For testing if a variable is an float.
is_int() For testing if a variable is an integer.
is_null() For testing if a variable is set to NULL.
is_numeric() For testing if a variable is a number or a numeric string.
is_string() For testing if a variable is a string.

For Example

if (!is_numeric($f_age)) {
    echo "<p>You must enter a number!</p>";
}

Further Information

9.3.4: Redirecting the Browser

  • Sometimes you want to redirect a browser to another page
  • You can accomplish this with the HTML refresh meta tag
  • <meta http-equiv="refresh" content="5;URL=http://bye.com">
    
  • A faster and less obvious method is to use the PHP header() function
  • The header() function sends a "raw" HTTP header to the browser
  • To use the header() function for redirection, you code something like:
  • header("Location: http://www.edparrish.com/");
    
  • Note that HTTP/1.1 requires an absolute URI as an argument to Location:
  • Thus, if you want to redirect to a page named login.html in the same directory, you should use something like:
  • http://localhost/~cis165/login.html
  • However, absolute URLs are not portable
    • When you move your code from one computer to another, the hostname and path can change
  • To resolve this problem, you ask the server for its name
  • $host = $_SERVER['HTTP_HOST'];
  • To get the file location to the current directory, you can use:
  • $path = dirname($_SERVER['PHP_SELF']);
  • Thus, to redirect the browser to a page named login.html located in the current directory:
  • $host = $_SERVER['HTTP_HOST'];
    $path = dirname($_SERVER['PHP_SELF']);
    $file = "login.html";
    header("Location: http://$host$path/$file");
    
  • You can write a function to handle the details like the following:

<?php
function redirect($url) {
    
$url trim($url);
    
$absURL "Location: ";
    if (
substr($url01) == "/") {
        
$absURL .= "http://".$_SERVER['HTTP_HOST'];
    } elseif (
strtolower(substr($url07)) != "http://") {
        
$absURL .= "http://".$_SERVER['HTTP_HOST'];
        
$absURL .= dirname($_SERVER['PHP_SELF'])."/";
    }
    
$absURL .= $url;
    
header($absURL);
    
// Make sure nothing else happens
    
die("Could not redirect");
}
?>

  • Using this function, you can redirect the browser in a number of ways:
  • redirect("http://www.edparrish.com");
    redirect("/index.html");
    redirect("../index.php");
    redirect("login.html");
    
  • Normally, you place the redirect() function in a separate include file
  • However, doing so means that you need to use a function named ob_start()
  • Place the ob_start() function call at the start of your page

Important Note

  • The header() function must be called before any output is sent to the browser
  • This includes:
    • HTML tags
    • Blank lines or even a single blank space
    • Any other content
  • Avoid this by checking your redirection conditions at the very start of a page
  • Also, you can prevent many problems by placing ob_start() at the top of any page that uses a redirect
  • A common programming error is to have include files before header() is called that add unintentional spaces or blank lines to a page
  • Do NOT commit this damaging error!

9.3.5: Summary

  • PHP has many built-in functions that are useful writing web pages
  • It is best to use a built-in functions, when available, rather than writing your own
  • We looked at using rand() to load random images
  • Also, we looked at how to test a variables state and type
  • Finally, we looked at how to redirect a user using the header() function

Exercise 9.3

In this exercise we explore redirecting the browser to another web page.

Specifications

  1. Save the login.html and logincheck.php files shown below in your public_html directory.
  2. Add code to logincheck.php that reads the form variables and verifies that the login and pwd values match those that you specify.
  3. If both the login and password are correct, then print an appropriate message.
  4. You have successfully logged in.
  5. If either the login or password are incorrect, redirect the user back to the login.html page so they can try again.
  6. Submit your logincheck.php file as the answer to this exercise.

File: login.html

<html>
<head> <title>Login Form</title> </head>
<body>
<h1>Please Login</h1>
<form action="logincheck.php" method="post" >
<p>Username:
<input type="text" size="15" maxlength="20" name="login">
<br>Password:
<input type="password" size="15" maxlength="20" name="pwd">
</p>
<br> <input type="submit" value="Click To Login">
<input type="reset" value="Erase and Restart">
</form>
</body>
</html>

File: logincheck.php

<?php
// debug code -- remove when completed
echo "<pre>";
var_dump($_REQUEST);
echo 
"</pre>";

// enter your code here

?>

9.4: Organizing Web Pages

Objectives

At the end of the lesson the student will be able to:

  • Discuss how to organize web pages using functions
  • Use functions with include and require statements

9.4.1: PHP Inside HTML

  • Easiest approach is to add PHP code within HTML code
    • Create HTML pages using the usual techniques
    • Add in PHP where needed to for dynamic capabilities
  • For example:
  • <html>
    <head>
    <title>Today's Date</title>
    </head>
    <body>
    <p>Today's date is: <?php echo date('Y/m/d'); ?></p>
    </body>
    </html>

  • This is a good technique for those new to programming
  • However, it becomes less convenient over time as the complexity of a site grows
  • Pages become harder to maintain because of duplicate HTML and PHP code

When to Use This Technique

  • Simple web page
  • Very little PHP is needed

9.4.2: HTML Inside PHP

  • The opposite approach is to put HTML inside of PHP code
  • For example, converting the code from the previous section:

<?php
echo "<html>\n";
echo 
"<head>\n";
echo 
"<title>Today's Date</title>\n";
echo 
"</head>\n";
echo 
"<body>\n";
echo 
"<p>Today's date is: ".date('Y/m/d')."</p>\n";
echo 
"</body>\n";
echo 
"</html>\n";
?>

When to Use This Technique

  • Longer or more complex web pages
  • Much of your page content is generated dynamically
  • You can benefit from organizing pages into functions

9.4.3: Grouping Repeated Code into Functions

  • One of the advantages of putting HTML inside of PHP is that you can organize repeated code into functions
  • For instance, we can write some functions to create HTML tables

<?php
// Returns HTML to begin a table.
function beginTable($tableAttr "") {
    
$html "<table";
    if (
$tableAttr$html .= " $tableAttr";
    
$html .= ">\n";
    return 
$html;
}

// Returns HTML to end a table.
function endTable() {
    return 
"</table>\n";
}

// Returns a row of table data from an array of data.
// If item is_array() then assume list($item, $attr)
// Adding attribute 'th' will cause use of th tag
function makeRow($rowList$cellAttr "") {
    
$html "<tr";
    
$html .= ">\n";
    foreach (
$rowList as $item) {
        
$attr $cellAttr;
        if (
is_array($item)) {
            list(
$item$attr) = $item;
        }
        
$tag "td";
        if (
"th" === strtolower(trim($attr))) {
            
$tag "th";
            
$attr $cellAttr;
        }
        
$html .= "  <$tag";
        if (
$attr$html .= " $attr";
        if (
$item) {
            
$html .= ">$item</$tag>\n";
        } else {
            
$html .= ">&nbsp;</$tag>\n";
        }
    }
    
$html .= "</tr>\n";
    return 
$html;
}

// Returns many rows where $set is an array of arrays
function makeSet($set) {
    
$html "";
    foreach(
$set as $field) {
        
$html .= makeRow($field);
    }
    return 
$html;
}
?>

  • We can put these functions in a separate file in our includes directory
  • To use the functions, we include them in our main page
  • Using included files, we can create complex pages with very little code

<?php
require_once("includes/tablelib.php");

$title "Table Function Demonstration";
require(
"includes/header.php");

echo 
"<h1>$title</h1>";

// Example of briefly switching to HTML mode
?>
<p>This is an example of using functions to
repeat commonly-used pieces of HTML code. It
builds a table, like this one.</p>
<?php

// Show table with labels on the left
echo beginTable("border=\"1\"");
echo 
makeRow(array(array('Step''th'),
             array(
'Description''th')),
             
'bgcolor="#DCDCDC"');
echo 
makeRow(array(array('1.','th'), 'Begin table'));
echo 
makeRow(array(array('2.','th'), 'Make rows'));
echo 
makeRow(array(array('3.','th'), 'End table'));
echo 
endTable();

// Example of heredoc
echo<<<HTML
<p>The functions allow you to draw all HTML
tables in the same way. To change the look of
all tables, you need only edit the functions.</p>

HTML;

// Show a table with labels on top
echo beginTable("border=\"1\"");
echo 
makeSet(array(
    array(array(
'Artist''th'), array('Song''th')),
    array(
'The Beatles''Let It Be'),
    array(
'Creed''Are You Ready?'),
    array(array(
'Squirrel Nut Zippers',
                
'bgcolor="cyan"'),
          
'Fat Cat Keeps Getting Fatter')
));
echo 
endTable();

require(
"includes/footer.php");
?>

9.4.4: Using Heredoc

  • Note that you can put chunks of HTML within the PHP code
  • You just close the PHP tag, write the HTML, and open new PHP tags
  • <?php
    // PHP code
    ?>
    Write the HTML code here
    <?php
    // PHP code
    ?>
    
  • Another technique is to use the heredoc syntax
  • <?php
    // PHP code
    print<<<identifier
    HTML code
    identifier;
    // PHP code
    ?>
    
  • Heredoc is just another way to delimit strings
  • Like double-quoted strings, the values of PHP variables are displayed
  • The added advantage of Heredoc is that you can use double quotes
  • Note that the closing identifier must be flush left on a line by itself

Example Using Heredoc

<?php
$login 
"mylogin";
$pwd "password";
print<<<HTML
<html>
<head> <title>Login Form</title> </head>
<body>
<h1>Please Login</h1>
<form action="echo.php" method="post" >
<p>Username:
<input type="text" size="15" name="login" value="$login">
<br>Password:
<input type="password" size="15" name="pwd" value="$pwd">
</p>
<br> <input type="submit" value="Click To Login">
<input type="reset" value="Erase and Restart">
</form>
</body>
</html>
HTML;
?>

9.4.5: Organizing Pages with Functions

  • Previously, we decided to use include files for repeated code
  • The included files can include commonly used functions as well
  • Another use for functions is to enhance the organization of our web pages
  • The following is a template to use for pages containing forms

Page Template Example

<?php
ob_start
();
require_once(
"includes/redirect.php");

// The page starts and stops with this function call
main("A Well-Organized Page");

// Page control logic
function main($title "") {
    if (isset(
$_POST["submit"])) {
        
$error checkForm();
        if (!
$error) { // data is OK
            
saveData();
            
redirect("/index.html?it=worked");
        }
    }
    require(
"includes/header.php");
    
showContent($title);
    require(
"includes/footer.php");
}

// Check the input form for errors
function checkForm() {
    
$error false;
    
// Put code to test form values here
    
return $error;
}

// Save the data
function saveData() {
    
// Save in database (or whereever) here;
}

// Display the content of the page
function showContent($title) {
    echo 
"<h1>$title</h1>";
    
// Put page info and form here
echo<<<HTML

<form action="mainfun.php" method="post">
<input name="submit" type="submit" value="Submit">
</form>

HTML;
}
?>

  • Notice how the entire page has one entry point: main()
  • All supporting functions follow the main() function
  • The main() function contains the logic to control the entire page
  • Related code is easily organized into functions
  • The page does not have any hard-to-find global code
  • Next week we will use this page structure to make "user-friendly" forms

Instructions for Using the Page Template

  1. Save the page template code above as your page name and verify that the page works.
  2. Change the title to the title you want.
  3. main("A Well-Organized Page");
  4. Change the page that you want the user to go to if the data they enter is correct.
  5. redirect("/index.html?it=worked");
  6. Add your page content in the showContent() function.
  7. Make sure that the action of your form is the name of your current page.
  8. <form action="yourpage.php" method="post">
  9. Also make sure that the name of your submit button is "submit".
  10. <input name="submit" type="submit" value="Submit">
    
  11. Verify that your page still works.
  12. Add error checking to checkForm() using $_REQUEST or $_POST to read the form variables. For example:
  13. function checkForm() {
        $error = false;
        // Put code to test form values here
        $num = trim($_REQUEST['num']);
        if ($num < 1 or $num > 10) {
            $error = true;
        }
        return $error;
    }
    
  14. Add the statements to save data in the saveData() function.
  15. See lesson 7.3.1 for instructions on saving data.

9.4.6: Summary

  • Easiest approach to integrating HTML and PHP is to add PHP inside HTML
    • However, PHP pages with large amounts of code are harder to maintain
    • Only use when you Web site has few pages and little PHP code
  • Putting HTML inside of PHP code is more productive for Web applications
    • You can modularize your code using functions
    • You can still use chunks of HTML code where appropriate
    • Easier to make changes that apply to the entire site
  • Place all your code that repeats across pages in separate files
    • Use include files for repeating code
  • Organizing your pages with functions makes the logic of a page easier to see

Exercise 9.4

In this exercise we create a single-page form from the two-pages of the previous exercise.

Specifications

  1. Save the following code in a file named login.php.
  2. Move your code from the previous exercise, both the login.html and logincheck.php, to the login.php file such that all the code is in this one file.
    • Put all HTML code from login.html in the showContent() function.
    • Put the decision code for a valid login in the checkForm() function.
    • There is no data to save from this form, so you can leave the saveData() function empty.
  3. Verify that the login.php page functions correctly.
  4. Submit your new login.php page as the answer to this exercise.

<?php
ob_start
();
require_once(
"includes/redirect.php");

// The page starts and stops with this function call
main("A Well-Organized Page");

// Page control logic
function main($title "") {
    if (isset(
$_POST["submit"])) {
        
$error checkForm();
        if (!
$error) { // data is OK
            
saveData();
            
redirect("/index.html?it=worked");
        }
    }
    require(
"includes/header.php");
    
showContent($title);
    require(
"includes/footer.php");
}

// Check the input form for errors
function checkForm() {
    
$error false;
    
// Put code to test form values here
    
return $error;
}

// Save the data
function saveData() {
    
// Save in database (or whereever) here;
}

// Display the content of the page
function showContent($title) {
    echo 
"<h1>$title</h1>";
    
// Put page info and form here
echo<<<HTML

<form action="mainfun.php" method="post">
<input name="submit" type="submit" value="Submit">
</form>

HTML;
}
?>

Wrap Up

Home | WebCT | Announcements | Course info | Expectations | Schedule
Project | Help | FAQ's | HowTo's | Links

Last Updated: December 11 2005 @22:06:03