PHP technology
· Running PHP scripts
· Basic PHP script
· Checkpoint
· PHP tags and lines of code
· Sending text to the browser
· PHP syntax overview
· Sending quotes inside quotes
PHP variables
· Case sensitive
· Types of variables
· Control of variable type
PHP arrays
· Do you want arrays?
· How to create an array
· Associative arrays
· Multidimensional arrays
PHP functions
· Defining functions
· Functions return values
· Global variables
· Local variables
· Single quotes
· Rendering variable names
· String concatenation
· Using variables in HTML
· String functions
· String examples
· Checkpoint
· Checkpoint
PHP control structures
· The PHP if conditional
· The PHP for loop
· The PHP switch conditional
PHP and HTML forms
· Has a variable been defined?
· Defining hidden variables
· Variables in conditionals
· HTML form example
· Textarea warning
· Spoof a POST
PHP e-mail
· PHP script calls itself
· Sending PHP email
· Sending HTML in e-mail
· Example HTML in e-mail
Loading Excel with PHP
Data in text files
· Content in text files
· Scripting content from file
· Writing content into file
· PHP file upload
· PHP lists in file
· Scripting PHP lists
· Writing PHP lists
· Handling 'special' characters
· Text database
· Tilde-delimited file
· Table from database
Creating iframe html
· Fill table with database
XML scripting with PHP
· PHP uses XSLT sorts
· XSLT customization
Secure PHP programming
· Security issues
Mastery test
Top of page
References
PHP Manual
· General
· Arrays
· Strings
· Files
· HTTP/cookies
· Date/time
· Mail
· Sessions
Other PHP
· PHP tutorial by Zend
· PHP tutorial by FreeWebmasterHelp
· PHP error checking
· Advanced PHP tutorial
· 10 PHP tips, Builder.com
· PHP and XML, Builder.com
· MySQL.com
· O'Reilly PHP
· PHP FAQ
Navigation

43. Introduction to PHP

PHP technology  (click any heading below to return here)

PHP, like VBScript, is a server-side scripting language, and it performs many of the same tasks as VBScript. For example, you can generate HTML code with PHP, save information to a database, program cookies, and even send email messages.

PHP, unlike VBScript, is an open-source product and is extremely popular on Apache (Unix) servers worldwide. The latest release of PHP, level 7, has convinced many that PHP outruns VBScript. This statement may be true, but its chief advantages for us include its extreme popularity, wide variety of built ins, huge libraries of free source code, excellent user forums, and close similarity to JavaScript syntax.

Due to the length of time you have in this course, we will not be covering MySQL. It is a popular open-source database held in high regard by the Web community. Although it is freeware, MySQL is powerful and reliable, and it is a common sidekick to PHP.


Running PHP scripts

Just as ASP requires software installation on the Web server, so does PHP. In order to use PHP, your Web server must have PHP installed. The client-side portion of this course has relied on your browser's ability to run the examples. With server-side topics, however, your Web server must be employed for running the PHP examples from these pages, so you will be asked to copy and paste the examples.

If you do not have ASP/IIS available on your server, then it is very likely that PHP is installed.

When you see a PHP script on one of the course pages, highlight and copy it. Next, save the code under the suggested filename. Upload it to your Web folder, and run it from there by entering the URL into the browser address bar.

There is a small script to begin our next PHP exercise. It will confirm whether PHP is installed and will show you the version number. Hopefully, version 4 or later is installed. Our examples have been tested with version 5.

Due to the number of topics we cover in this course, there is not sufficient time to cover PHP thoroughly. There is time, however, to:

  • learn some great functions
  • introduce the syntax and some common syntax errors
  • provide tutorial and reference links for future study

Because we will use complete examples, you be able to use some handy techniques by the time you finish this lesson.


Basic PHP script

Like VBScript and JavaScript, PHP must be coded within script tags. Below is a program for you to copy and upload to your server with the name "test.php." Once you have uploaded the file, run it to learn which version, if any, of PHP is installed.

<!DOCTYPE html>
<html>
<head>
<html lang="en-US">
<meta charset="UTF-8" />
<title>Test PHP on the server</title>
</head>
<body>

<?php          // opening tag -- required

phpinfo();      // a built-in function call (a statement)

?>              // closing tag -- required

</body>
</html>
All php statements MUST end with a semicolon.


Checkpoint    (answer then click)

Highlight and copy the test.php script. Next, save it and upload it to your Web folder. You may run it now, and return here to compare your output with ours. You can see this screen and the test.php results together by resizing the browser windows, or you can just cycle back and forth between them with Alt-Tab.


PHP tags and lines of code

Always start any PHP scripting with the PHP containers <?php and ?>. Always end each line of the script with a semicolon.

<?php           // opening tag -- required

phpinfo();      // a built-in function call (a statement)

?>              // closing tag -- required


Sending text to the browser

Most scripts prepare material for the user to see on the browser. Such scripts must send HTML markup to the browser since that is the language the browser uses to display material. Write a PHP script to create an HTML page for the browser. Here is a simple example.

<?php

print "<h3>Sending text to the browser</h3>";

print "<p>Most scripts prepare material for the user to see ...</p>";

?> 

All text sent to the browser must be inside quotes. Use the print built-in function to send the text. Most of the time you will include tags in the text for the browser to render. Always end each line with a semicolon.


PHP syntax overview

Now we will have a quick review of the key points we have learned thus far. Then, we will learn how to send text containing quotes to the browser.

Review of key points:

  •  All PHP scripts are saved in files named *.php
  •  Scripts must be run/tested/debugged after uploading
  •  The PHP container tags are <?php and ?>
  •  All PHP statements must end in a semicolon
  •  Script HTML statements using the PHP print " " built-in


Sending quotes inside quotes

At times, you will want the user to see quotation marks in the text. For example, quotes must be displayed when quoting someone. Mishandled quotes cause syntax errors because PHP already expects to see a pair of quotes surrounding your print argument. The following causes a syntax error:

<?php
print "<p>...quotes sometimes, "As I know you will" ...</p>";
?> 

Internal quotes must be preceded by a slash. The slash can be used with any ambiguous character, as you will see later.

<?php
print "<p>...quotes sometimes, \"As I know you will\" ...</p>";
?> 

PHP variables

All variables must begin with a dollar sign $ followed by an alphabetic character or underscore. For example, $FirstName, $greeting, $_count, $Total.


Case sensitive

PHP is case-sensitive. Name your variables with upper and lowercase, and be consistent: $Firstname, $Greeting, $count, $total are not the same variables shown above.


Types of variables

Your first use of a variable establishes its type. Most of the time, you will begin by placing a value in the variable. The following variables are of the types string, integer and double, respectively:

$greeting = "Welcome back"
$_count = 23
$Total = 1456.75


Control of variable type

Information you receive from a form (that is, data submitted by an HTML page to your script), may need to be molded into the appropriate data type. Numeric data sent in a text field will be a string, not an integer or a double, as you might expect. You need to coerce the type for your own script purposes to prevent errors.

PHP variables contain integers, doubles, strings, booleans, objects, or arrays. You have four means of controlling the type.

  1. Define the variables and give them the appropriate value
  2. Coerce the type: $variable = settype( $variable, type );
  3. Coerce an instance by casting: $data = ( type ) $variable;
  4. Examples of coercion:
    • (integer) $variable; returns integers
    • (string) $variable; returns strings
    • (double) $variable; returns doubles


Error reporting - you control

The error_reporting() function sets the error_reporting directive at runtime. PHP has many levels of errors, using this function sets that level for the duration (runtime) of your script.

error_reporting() sets PHP's error reporting level, and returns the old level. The level parameter takes on either a bitmask, or named constants. Using named constants is strongly encouraged to ensure compatibility for future versions. As error levels are added, the range of integers increases, so older integer-based error levels will not always behave as expected.

<?php

error_reporting(0);     // Turn off all error reporting

// Report simple running errors
error_reporting  (E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting (E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
// This is the default value set in php.ini
error_reporting (E_ALL ^ E_NOTICE);

// Report all PHP errors (bitwise 63 may be used in PHP 3)
error_reporting (E_ALL);

?>

PHP arrays



Do you want arrays?

They are used, as in other languages, for holding lists of information conveniently under one variable name. When you need the 2nd item from an array named $score, you would use this syntax: $score[1]. Yes, arrays begin with index number zero. But they can also be indexed with names instead of numbers. See Associative arrays below.

The size of a PHP array is provided by the count function. It returns the number of items in an array, not the index of the last item.

        $size = count($score);


How to create an array

For simple arrays of static information, it is easiest to use a construct called array().

        $student = array( "Jim", "John", "Larone" );

PHP provides another convenience for creating arrays. You can omit the index number when filling an array with information. The following builds the same numerically indexed array as in the above example.


        $student[] = "Jim";
        $student[] = "John";
        $student[] = "Larone";


Associative arrays

If your don't like index numbered elements in your array, use a string index instead. Associative arrays are easier than numerically index arrays to use in many cases. I find $score[11] harder to remember consistently than $score["Test5"]. Create the string names at the time you create the array.

The associative index can be a literal (print $score["Test5"];) or a variable ($index="Test5"; print $score[$index];).


Multidimensional arrays

Think of these data structures as you would of records and fields in tables. The first dimension of a two-dimensional array is similar to records or rows in a table, the second is similar to columns or fields in a table.


        $roster[0]["name'] = "James Monroe";
        $roster[0]["EID'] = "J35tr";
        $roster[0]["Test1'] = 87;
        $roster[0]["Test2'] = 93;
        $roster[1]["name'] = "Larone Campbell";
        $roster[1]["EID'] = "La912";
        $roster[1]["Test1'] = 94;
        $roster[1]["Test2'] = 95;
        for( $i=0; $i < count($roster); $i++ )  {
             print $roster[$i]['name']." ".$roster[$i]['EID']."<br />";
        }   

Multidimensional arrays are sometimes used to hold the results of a query, and the query results array could be placed in a session variable to provide the query information across all Web pages in a site.

There are numerous built-in PHP functions for manipulating arrays. Further information is in the PHP manual.

PHP functions



Defining functions

A function is a self-contained block of code written to perform a discrete step in your logic. Use functions freely to modularize your scripts, and build an inventory of reusable script code.

Define a function by copying the code below. The formal argument $arg may not be necessary for your functions. The example is written to save typing time when writing HTML to the browser.

    function pl ( $arg ) {
        print "$arg<br />\n";
    }


Functions return values

Calculations and string manipulations can be returned by your functions. Use the result by placing the function reference on the right of the assignment operator, or inside a statement. Here is an example.

    $b = 33.6;
    $c = 2;
    $a = sumInt ( $b, $c );                       // call on the right
    pl ("<h4>Sum is =".sumInt( $b, $c)."</h4>");  // call in a statement
    function sumInt( $arg1, $arg2 ) {
        return intVal( $arg1) + intVal( $arg2 );
    }

Sum is =35


Global variables

Global variables are those variables used outside of functions. A global variable must be either declared outside of a function or received from a form submission.

These variables are not allowed inside of functions unless invited (how you do this is described below). This rule is really nothing more than a safety measure to make you aware of the scope of any changes to these variables. The usual scripting practice is to send information into functions through formal arguments, not by using global-scope variables.


Local variables

Local variables are created within a function and can be used within that function only. They are unavailable elsewhere and protected in this sense from careless change outside of the function boundary. Many languages have this feature.

Global variables may be accessed, in addition to the local variables, by making reference to them as global. Use this declaration inside a function.

       global $g_data1, $g_data2;


Single quotes

Although single quotes are handy in other languages for placing quotes within quotes, they serve a different purpose in PHP. They signify send literally what is contained in the single quotes. In other words, there will not be an inspection and replacement of the variable names with their contents. Do not use single quotes unless you understand this concept.


Rendering variable names

If you want the user to see a variable's name, rather than its contents, then you can use single quotes, or you can simply place a slash in front of the variable name.

print "$greeting, $FirstName";   // rendered: Welcome back, Hugh
print "$greeting, \$FirstName"   // rendered: Welcome back, $FirstName
/* the next two lines are described below */
$message = $greeting . ", " . '$FirstName';
print "$message";                // rendered: Welcome back, $FirstName

The syntax of comments is shown above in two forms:

  • As the last text on a statement line, use // to begin comment for one line
  • For multiple lines, use the container /* */.


String concatenation

Look at the $message= line above. It illustrates the effect of single quotes, and it introduces the catenation operator, the period.


Using variables in HTML

print "<h1>$greeting</h1>";

print "<p>You have visited here $_count times.</p>";

Before PHP sends the print to the browser, it looks for any variables you coded, and substitutes their values automatically.


String functions

Here is a brief list of built-in string functions that you will need to begin authoring PHP scripts. Note that all string functions begin counting characters with zero.

FunctionExampleNotes
substr$A=substr("Web Systems",4,10)
"Systems" returned
4 is the start,
10 is the length to return
strlen$E=strlen("PHP")
3 returned
find the number of characters
strtolower$A=strtolower($A)converts to lowercase
strtoupper$A=strtoupper($A)converts to uppercase
ergiergi($haystack,$needle)return true or false
if needle exists in haystack
str_replacestr_replace($needle,$with,$haystack)returns $haystack having all its
values of $needle replaced with $with
strpos$at=strpos
($haystack,$needle,$start)
return position of needle in
haystack
search beginning at start
strrpos$at=strrpos
($haystack,$needle,$start)
return last position of needle in
haystack search beginning at start
explode$array=explode($atChar,$A)separates a string into items
in an array using the atChar
implode$A=implode($glue,$array)joins all items in array into one
string each separated by glue
trim$B=trim($B)remove spaces before and after

Examples of these functions are next.


String examples

<?
print "<html><body><br />";

$greeting="Good to see you're back";
/*         01234567890123456789012  */

$CSV="013458789,Bill,Jones,bj@mail.panam.edu";

$PathFileName="http://www.php.net/manual/en/function.eregi.php";


$A=substr($greeting,0,3);           // string positions are 0,1,2,3,..

$B=substr($greeting,0,15) . substr($greeting,16,1) . substr($greeting,18,10);

$C=strrpos($PathFileName,"/");      // look for the last slash in a URL

$D=substr($PathFileName,$C+1,99);   // grab the file name from the URL

$Data=explode(",",$CSV);  // break apart the comma-separated-values into array

print "1. $A";                      // 1. Goo
print "<br />";
print "2. $B";                      // 2. Good to see your back
print "<br />";
print "3. $C";                      // 3. 28
print "<br />";
print "4. file name is $D";         // 4. file name is function.eregi.php
print "<br />";
print "$CSV";                       // 013458789,Bill,Jones,bj@mail.panam.edu
print "<br />";                     // array item 0 =013458789
for ($k=0; $k < count($Data); $k++) {  // array item 1 =Bill
    print "array item $k = $Data[$k]";  // array item 2 =Jones
    print "<br />";                 // array item 3 =bj@mail.panam.edu
}
print "</body></html>";
?>


Checkpoint    (answer then click)

We need two pages of checkpoints for the string examples you just saw. Answer these questions by referring back to the previous page of examples. Click to check your work.

  1. Explain how the 012345... that was below $greeting could help you script substrings of $greeting.
  2. The $CSV string has fields of information like SSN, names, and email separated by commas. Why?


Checkpoint    (answer then click)

  1. The catenation operator and substring function were used to create $B. Is it good to see your back?
  2. There are five slashes in the URL $PathFileName. What function was used to locate the right-most slash?
  3. Because of explode$() we now have the CSV record divided into items of $Data[]. Which item holds the email?


PHP control structures

These structures are highly similar to JavaScript. Thus, only a few examples should be necessary to teach you their syntax.


The PHP if conditional

if ($TotalCost >= 50) {
    $TotalCost = $TotalCost - $Discount;
    $TotalDiscounted++;
}

if (strtoupper(trim($sex)) == "M"){  // notice use of functions
    print "Yes sir";
}else{
    print "Yes ma'am";
}

Another form of if is the immediate or inline result. Read the following line as "if $a> $b then return 1 otherwise return 0". The benefit of this structure can be realized by the second example.

($a> $b) ? 1 : 0 ;

$greet = ($sex=='f') ? "girl" : "boy";
print "Hello, $greet";


The PHP for loop

for ($k=0; $k < count($Data); $k++) {   // count() returns # items

    print "array item $k = $Data[$k] <br />";
}


The PHP switch conditional

switch ($ContactHow) {
    case "Telephone":
        print "Please enter a daytime phone number.";
        break;  // break jumps out of switch
    case "E-Mail":
        print "Please enter your E-Mail address.";
        break;
    default:    // default: is executed if no match above
        print "Select how you want to be contacted.";
        break;
}

PHP and HTML forms



Has a variable been defined?

We ask the question above most often when programming scripts to receive form data. The script you name in the form tag attribute...

<form action="http://www.site.com/form.php"...

...will be sent the named form controls (text boxes, lists, check boxes, etc). For safety, we always ask at the top of the script if one of the form controls has been defined. If not, we will not run the rest of the script because the script was run when it should not have been.


Defining hidden variables

Here is an example of a named form control "EmailSubmit" that will be given a value of true to signify that the email form was run. If form.php is requested from another form, then EmailSubmit will be false, since it is not a control on any other form.

<input type="hidden" name="EmailSubmit" value="true" />


Variables in conditionals

The HTML form controls on this page will submit their named variables to form.php, where we can check to see if the PHP script should be run. That is, was the script requested from the form we think it was? Here is the PHP logic.

if (isset($MailSubmit)) { .... ;}
Because the correct form placed "true" in EmailSubmit, we can use this clear conditional to query whether the expected form generated the request for the PHP program.

Like other programs, PHP will run its statements in the sequence in which they are encountered. When HTML is also present, new Web authors can get confused. Add the two computers (client-server) into the picture with the two languages (if you are not confused yet).

Another type of variable definition must be introduced. Because variables can be passed in the URL, it is possible that a script expects a variable it cannot get from the URL, and a run-time error is produced. This can be avoided by using isset() as in the conditional below.

if (!isset($_REQUEST["txtCustomer"])) { .... ;}  // ask if NOT sent in URL


HTML form example

We learned to markup forms and assign each control (text box, list, check box, etc) a specific name. Those names are recognized by PHP.

<form name="frmNewCustomer" action="form.php" method="get">
    Enter your email address
        <input type="text" name="txtCustomer" maxlength="40"/>
    and Password
        <input type="password" name="txtPassword" />
    <input type="submit" value="Submit" />
</form>

If your form action terminates in a PHP script (form.php for example), you can enjoy fully automatic variable names in the script.

Inside the PHP script named form.php, the two variables $txtCustomer and $txtPassword will be available automatically. Here is a script that looks up the customer and confirms their password.

<?php           // opening tag in form.php
$Customer = $_REQUEST["txtCustomer"];
$Password = $_REQUEST["txtPassword"];
$Record = lookup( $Customer )
if ( $Record && confirmPassword ( $Password )) { // process customer
}

?> 

If this concept is not clear, the email example script that uses forms should help.


Textarea warning

Users can type their data into a textarea form control you provide, and they can include the Enter key to break lines. The Enter key creates a CRLF (carriage return, line feed) in the stream of data transmitted. This can cause problems.

If you are storing the transmitted data in a text file (described later), it is necessary to replace the CRLF with the HTML line break tag <br /> before you write it into the file. Otherwise only the first part of the text will be saved to file. Here is the code necessary to perform the replacement and solve the problem for one transmitted textarea field: txtArea.

$crlf = chr(13).chr(10); // storing the crlf for search/replace below

$txtArea = str_replace($crlf, "<br />", $txtArea);

Another problem will arise if the user enters an apostrophe ('). PHP will automatically add a backslash in front of the ', making your output look like this "the boy\'s toys" instead of this "the boy's toys". The following PHP function will correct this as well.

$txtArea = stripslashes( $txtArea );

Refer to the PHP strings manual for more information.


Spoof a POST

Suppose you need to send credit card approval requests via a form post. This is typical and easy enough to do without having to write scripts. However, if you want to preserve the form data entered by your user you will need to involve INTERMEDIATE scripts to update tables and/or session variables -- to preserve state.

Create the original html form with method="post" as usual. In place of the action="https://www.approvethiscard.com" insert the name of a script file you write to update tables and/or session variables, then later in the script spoof a post of the form data to approvethiscard.com.

<?php

// this script shows how to 'spoof a post'

// in the upper part of this script you will
// need to receive some values passed by
// a calling post script, then load the passed
// data into session variables or tables.

// note the escaped quotes around \"$var1_value\"
// these preserve any blanks in the value

die ("<html>
<body onload='top.hiddenform.submit();'>
<form name='hiddenform' action='http://www.approvethiscard.com' method='post'>
<input type='hidden' name='var1' value=\"$var1_value\">
</form>
</body>
</html>");
?>

PHP email



PHP script calls itself

Here is a logical three step process that we will use to take in email messages and send them. The sequence, or order of execution, is important.

  1. A user fills in the HTML form with an email message
  2. PHP checks the form for a message
  3. PHP sends the email message

Here is the order in which we will script the sequence. We place all operations in a single script. See the source below.

  1. PHP checks the form for a message
  2. PHP sends the email message
  3. A user fills in the HTML form with an email message

All three steps will be scripted in one PHP file, which is shown next. Our goal is to have a single PHP script do all three steps.


Sending PHP email

<!DOCTYPE html>
<html>
<head>
<html lang="en-US">
<meta charset="UTF-8" />
<title>WebSys: Web systems development</title>
<meta name="author" content="Hugh Poynor" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
</head>
<body>

<form name="frmEmail" method="get" action="mail.php">
<table border="0" cellspacing="0" cellpadding="5">
<colgroup style="text-align:right" span="1"></colgroup>
<tr><td style="text-align:right">To Email Address:</td>
<td><input type="text" name="MailTo" size="50"></td></tr>
<tr><td style="text-align:right">From Email Address:</td>
<td><input type="text" name="MailFrom" size="50"></td></tr>
<tr><td style="text-align:right">Subject:</td><td>
<input type="text" name="Subject" size="50"></td></tr>
<tr><td style="text-align:right">Message:</td><
td><textarea name="Body" rows="6" cols="40"></textarea></td></tr>
<tr><td colspan="2" style="padding:12px 0px 8px 0px;text-align:center">
<input type="hidden" name="EmailSubmit" value="true">
<input type="submit" name="submit" value="Send"></td></tr>
</table>
</form>
<script>document.frmEmail.MailTo.focus()</script>
<?php
if( isset($_REQUEST["EmailSubmit"]) ){
    $MailSubmit = $_REQUEST["EmailSubmit"];
    $ToAddr = $_REQUEST["MailTo"];
    $MailSubject = $_REQUEST["Subject"];
    $MailBody = $_REQUEST["Body"];
    $FromAddr = $_REQUEST["MailFrom"];
}
if (isset($MailSubmit)) {
    if ($ToAddr) {
        if (mail($ToAddr, $MailSubject, $MailBody, "From: <$FromAddr>")) {
            print ("<strong>Your email to ". $ToAddr. " has been sent!</strong>");
        } else {
            print ("<strong>Your email encountered a system error!</strong>");
        }
    } else {
        print ("<strong>Please enter the recipient's email address!</strong>");
    }
}

?>
To Email Address:
From Email Address:
Subject:
Message:


Sending HTML in e-mail

Most email we receive is plain text, but you may have received email that had colorful graphics and looked as good as a printed brochure or a Web page. It was a Web page. This part of the PHP lesson describes how to use the built in mail() function to send Web pages as e-mail.

mail($MailTo, $Subject, $Body, $Headers)

The last argument, $Headers, can contain several arguments if they are separated by \n\r (new line). This argument allows us to signify to the email client program that HTML is stored in the $Body. Here are some popular arguments you may use in $Headers. If you want to send attachments or need further information, read the PHP Manual on mail().

$Headers .= "From: Your name <name@mail.edu>"."\r\n";
$Headers .= "Cc: personX@mail.edu"."\r\n";    // must be exact (Cc:)
$Headers .= "Bcc: personZ@mail.edu"."\r\n";  // must be exact (Bcc:)
$Headers .= "Content-Type: text/html; charset=iso-8859-1"."\r\n";

A short HTML page example follows.


Example HTML in e-mail

$Subject = 'Web page inside email';
$Body = '<html>........ use double quotes in markup ...</html>';
$Headers = "From: Morgan Law <author@BooksbyMorganLaw.com>"."\r\n";
$Headers .= "Content-Type: text/html; charset=iso-8859-1"."\r\n";
mail($ToAddr, $Subject, $Body, $Headers);
// note: $ToAddr is derived from the text box below, not in this code.
// the $ToAddr can include the recipients name, see next line
// script this: $ToAddr = "Jimmy Cricket <" . $ToAddr . ">\r\n";
Send page to:
Visit our Web site BooksbyMorganLaw.com


Loading Excel with PHP

Construct an HTML table and have it sent to the user's Excel client. This is another way of "downloading" data with a server script. It is more direct that sending XML or comma-delimited data. It DOES require the user to have an up-to-date version of Excel. Try it out.

<?php
 header("Content-type: application/vnd.ms-excel");
 header("Content-Disposition: attachment; filename=\"test.xls\"");
?>
<!DOCTYPE html>
<html>
<head>
<html lang="en-US">
<meta charset="UTF-8" />
<title>Load Excel from a PHP script</title>
<meta name="author" content="Hugh Poynor, PhD Ph.D." />
</head>
<body>
<table border="1" >
    <colgroup span="1" style='text-align:right'></colgroup>
    <colgroup span="1"></colgroup>
    <colgroup span="1" style='text-align:right'></colgroup>
    <tr><th>Qty</th><th>Item</th><th>Total</th></tr>
    <tr><td>3</td><td>Small wigits</td><td>23.00</td></tr>
    <tr><td>1</td><td>Medium wigits</td><td>9.00</td></tr>
    <tr><td>7</td><td>Large wigits</td><td>221.00</td></tr>
</table>
</body>
</html>

Data in text files



Content in text files

The imaginary CNN news piece will be rewritten daily as fresh stories break. We want a CNN department to place all the markup for the small "On CNN TV" region in a text file on the Web server. The larger page will contain many other regions and their content as well.

The small text file will be called newsanalysis.txt, and it will contain all the HTML markup and content necessary to fit into the allotted space on the large page. Here is that markup in the text file and how it looks when rendered alone.

<img style="float:left" src="images/web-wolf_blitzer.jpg"
       alt="Wolf head" width="66" height="51" border="0" />
<a href="#" style="color:blue;font-weight:bold">
Wolf Blitzer Reports:</a><br />
Operation Anaconda: mission accomplished?<br />
Or will al Queda rise to fight again? Join Wolf Blitzer
in the "War Room." <strong>(7p.m. E.T.)</strong>
Wolf headWolf Blitzer Reports:
Operation Anaconda: mission accomplished?
Or will al Queda rise to fight again? Join Wolf Blitzer in the "War Room." (7p.m. E.T.)


Scripting content from file

The PHP source file below opens and reads newsanalysis.txt after a server connection is made. Then, it writes the contents of the file (which is HTML) to the page. It is a standard practice to mix PHP and HTML on a PHP page. We have colored the HTML green to make it clearer.

<html><head><style type="text/css">
div.newsanalyst { font-family:verdana,sans-serif; font-size:8pt;
line-height:120%;width:337px;height:55px;border:1px silver solid}
</style></head><body>
<div class="newsanalyst">
<?php
$f = "../db/newsanalysis.txt";
$fs = fopen( $f, "r");
$news = fgets( $fs, 9999 );      // read one line from file
while (!feof($fs)) {             // loop required to read more than one line
    print $news;                 // write to the page
    $news = fgets( $fs, 9999 );  // read one line from file
}                              // close loop
print $news;                      // write to the page
fclose ( $fs );
?>
</div></body></html>

For a real page of news stories this process would be repeated many times, once for each region on the news page, and the source code above would need to open and read many text files.

Parallel code for ASP can be found in the ASP lesson.


Writing content into file

Note if you are operating on a Unix server: the files you write to (newsanalysis.txt in the example below) must be set to allow the writes. Until you change the Remote File Permissions with chmod (or an equivalent utility) to allow the file to be written into your PHP script will throw an error.

Unix chmod

The PHP source file below writes into newsanalysis.txt after a server connection is made. It pulls the information from the html form named news.html and  story.php then writes it into the newsanalysis.txt text file. We have colored the HTML green to make it clearer.

news.html

<html><head><title>News Story</title></head>
<body><h3>Enter in News story</h3>
<form name="frmnews" method="post" action="story.php">
<table border="0" cellspacing="0" cellpadding="5">
<tr><td>Story :</td><td><textarea name="newStory" rows="5" cols="50">
</textarea></td></tr>
<tr><td colspan="2" align="center">
<input type="submit" value="submit"> </td></tr>
</table></form></body></html>

story.php

<?php
$story = $_REQUEST["newStory"];
$f = "../db/newsanalysis.txt";
$fs = fopen( $f, "w");  //the w denotes writing (file mode)
fwrite ( $fs, "$story\r\n");
fclose ( $fs );
?>

Here is a summary of all the File modes for the fopen( ) function.


ModesMeaning
rRead mode - Open for reading, beginning from start of file
r+Read mode - Open the file for reading and writing, beginning form the start of file
wWrite mode - Open the file for writing, beginning from start of file. If the file already exists, delete the existing contents. If it does not exist, try and create it
w+Write mode - Open the file for writing and reading, beginning from the start of the file. If the file already exists, delete the existing contents. If it does not exist, try and create it.
aAppend mode - Open for appending (writing) only, starting from the end of the existing contents, if any. If it does not exists try and create it
a+Append mode - Open the file for appending (writing) and reading, starting from the end of the existing contents, if any. If it does not exist, try and create it


PHP file upload

The PHP source file below uploads files from one directory to another. In this example, we are uploading a text file for a news article. I have written both the html form called up.html and the php file named upload.php.  For security reasons, file uploads can be restricted in the php.ini located in the server directory. For uploads to work you must turn PHP safe mode off and turn on register_globals. It is recommended to have some restrictions on who is allowed to upload files to the server. Some ASP installations, such as the McCombs Business School, do not allow file uploads. Other server installations may not support your requests for changing any of their PHP security levels.

up.html

<html><head>
<title>Upload new files</title>
</head><h1>Upload new news files</h1>
<form enctype="multipart/form-data" action="upload.php"method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="200000">
Upload This File: <input name="userfile" type="file">
<input type="submit" value="Submit" />
</form></body></html>

upload.php

<head><title>Uploading....<title></head>
<body><h1>Uploading file....</h1>
<?php
$filename = $_FILES['userfile']['tmp_name'];
$realname = $_FILES['userfile']['name'];

   if ($_FILES['userfile']['size'] == 0)
      {echo "Problem: File is of zero length"; exit;}

   if ($_FILES['userfile']['type'] != "text/plain")
      {echo "Problem: file not plain text"; exit;}

   if (is_uploaded_file($filename))
      {copy($_FILES['userfile']['tmp_name'], ".\\news\\".$realname);
      echo ("<b> File successfully copied! </b>");
   } else {
   echo "Possible file upload attack:
              filename ".$_FILES['userfile']['name'].".";
}
?>

</body><head>

PHP lists in file

Let's continue to study text files. Text files are easy to use, easy to understand, and cheap. As long as we have fewer than about 200 records, text files will be sufficient to meet our needs for storage and retrieval.

A file named fruit.txt holds a list of fruit. Visitors to the Web page are expected to choose from a pull down list on an HTML page. To make the example clearer, only the list appears on the page.

Apples
Apricots
Bananas
Berries
Cherries
Guavas
Plums
Watermelons

This example uses PHP to read fruit.txt and to insert the records into the pull down list. It then sends the page to the browser. Source code for this example follows.

Parallel code for ASP can be found in the ASP lesson.


Scripting PHP lists

Here is the PHP source code for the pull down list of fruit. HTML markup has been color-coded green to distinguish it from the PHP script.

<html><body>
<form name="frmExample" method="get" action="">
<select name="fruit">
<?php
$TheFile = fopen ("../db/fruits.txt", "r");
if($TheFile){
    $Fruit = strval(fgets($TheFile, 4096));
    while (!feof ($TheFile)) {
        print "<option>" . $Fruit . "</option>";
        $Fruit = strval(fgets($TheFile, 4096));
    }
    print "<option>" . $Fruit . "</option>";
    fclose ($TheFile);
}
?>
</select> <input type='submit' value='submit' />
</form></body></html>

Parallel code for ASP can be found in the ASP lesson.


Writing PHP lists

Here is the HTML and PHP code to populate or write into fruit.txt text file. It pulls the information from the html form named fruit.html and  addfruit.php then writes it into the fruit.txt text file. We have colored the HTML green to make it clearer.

fruit.html

<html><head>
<title>Fruit</title>
</head><h1>Add another fruit</h1>
<form name = "frmfruit" action = "addfruit.php" method = "post">
<table border="0" cellspacing="0" cellpadding="5">
<tr><td>Fruit :</td><td><input type="text" name="Newfruit"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="submit" </td></tr>
</table></form></body></html>

addfruit.php

<html><body>
<?php
$Fruit = $_REQUEST["Newfruit"];
$TheFile = fopen ("../db/fruits.txt", "a");
fwrite( $TheFile, "$Fruit\n\r");
fclose ( $TheFile );
?>
The Fruit has been added</body></html>


Handling 'special' characters

Unwanted HTML syntax

With htmlentities() all characters which have HTML character entity equivalents are translated into these entities. Examples:

	& is converted to &amp;
	<  is converted to &lt;
	> is converted to &gt;
 

With html_entity_decode() all HTML entities are converted to their applicable characters. Examples:

	&amp; is converted to & 
	&lt; is converted to  <
	&gt; is converted to > 
 

Unwanted quotes

Data entered in HTML forms can be a problem when it contains quotes. Two examples of form data entered by visitors that cause file/database issues are as follows.

	Johnny O'Reilly
	William "Billy" Wang

The solution is a function to escape the quotes before storing in file/database, and another function to strip the escape sequence from the stored form data before you re-use it to display on a Web page.

The addslashes() function adds backslashes (the escape character) before characters that need to be quoted in database queries etc. These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

The stripslashes() function strips off backslashes. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\).

	$name = addslashes($_GET['names']);
	// write $name to file or db
	...
	// get $name from file or db
	print stripslashes($name);


Text database

Now we will see how a tilde-delimited text file (if it were comma-delimited it is called CSV by Microsoft) can be used to hold employee records and show them in a table on a Web page.


Tilde-delimited file

You can use any character to act as the delimiter or seperator, but the delimiter character should be something that certainly not occur in the input. I chose the "~". 

The fields of data are ID, FirstName, LastName, HireDate, ReviewDate, Salary, Sex and IsSelected. You will see how to read the records as text and split them into elements of an array. The array is coded $rec[], so $rec[3] is the element that holds HireDate.

1~James~Carlile~2/2/2001~10/13/2001~23200.00~M~1
2~Andrew~Frank~2/9/1997~2/9/1999~46276.92~M~1
3~Janet~Lydell~6/25/1994~6/25/1999~68674.72~F~0
4~Margo~ONiell~11/16/1994~11/16/1999~56834.25~F~0
5~Edward~Jones~11/17/1998~11/17/1999~62088.20~M~1
6~Harry~Jones~9/22/1978~10/1/1999~43920.23~M~1
7~Jimmy~Smith~2/24/2000~2/24/2001~55703.70~M~0
8~Hugh~Poynor~9/12/1989~9/30/1999~28923.08~M~1
9~Edward~Smith~3/6/2000~2/24/2001~25000.00~M~1

Parallel code for ASP can be found in the ASP lesson.


Table from database



<html><body>
<table border='1' cellspacing='0' cellpadding='5'
       width="440" style="border-collapse:collapse;
       font-family:sans-serif;">
<tr style="background-color:gainsboro"><th colspan="2">
Employee</th><th>Sex</th>
<th>Hired</th><th>Salary</th></tr>
<colgroup>
<col span="2" align="left" />
<col span="1" align="center" />
<col span="2" align="right" />
<?php
$oddColor='whitesmoke';
$evenColor='azure';
$ID=0; $FirstName=1; $LastName=2; $HireDate=3;
$ReviewDate=4; $Salary=5; $Sex=6; $IsSelected=6;
$TheFile = fopen ("../db/Employee.txt", "r");
if($TheFile){
    $row = 0;
    $Employee = strval(fgets($TheFile, 4096));
    while (!feof ($TheFile)) {
        $rec = explode("~",$Employee);
        if($row % 2 == 0) {
            $rowStart = "<tr style='background-color:".$evenColor."'><td>"; }
        else {
            $rowStart = "<tr style='background-color:".$oddColor."'><td>"; }
        print $rowStart;
        print $rec[$FirstName]. "</td><td>" ;
        print $rec[$LastName]. "</td><td>" ;
        print $rec[$Sex]. "</td><td>" ;
        print $rec[$HireDate]. "</td><td>" ;
        print "$".$rec[$Salary]. "</td></tr>";
        $row++;
        $Employee = strval(fgets($TheFile, 4096));
    }
    fclose ($TheFile);
}
?>
</table></body></html>

Parallel code for ASP can be found in the ASP lesson.

Creating iframe html


If your goal is to show the contents of a large html table in a scrolling format then use an iframe which has the scrolling attribute. Place the table in an html file by itself, named myTable.html. Markup an iframe in your main page like this:

<iframe src='myTable.html'  scrolling="yes"  width='?' height='?' >
</iframe>


Fill table with database

If you need to fill the html table with data from a database then you must use PHP (or ASP, Perl) to rewrite myTable.html and insert fields from the database into the html table data cells. To insure that the most recent data is reflected in myTable.html use the meta tags shown in the source below. The example source code was used to fill an html table from a MySQL table with names of people who planned to attend a picnic. People signed up (RSVP) on a Web page and the listing (table) of people planning to attend the picnic was immediately refreshed to show their names.

The steps not shown here are: (1) Use html to take in form data (people attending the picnic), and (2) Use PHP/MySQL to add the form data to a picnic table.

// Use PHP/MySQL to read the picnic table and create an html table

function picnicTable(){
	openDB();
	$sql="
		SELECT * FROM picnic
	;";
	$table = "
		<html>
		<head>
		<meta http-equiv='Pragma' content='no-cache'>
		<meta http-equiv='expires' content='0'>
		</head>
		<body>
		<table border='1'>
	";
	$table .= "";
	if( !$result = @ mysql_query($sql) ) die("SQL err ".$sql);
	while ($f = @ mysql_fetch_array($result)) {
		$table .= "
			<tr>
			<td>".$f[0]."</td>
			<td>".$f[1]."</td>
			</tr>
		";
	}
	$table .= "
		</table>
		</body>
		</html>
	";
	// open html file and rewrite contents.
	// the html file will be the source of an iframe.
	$fs = @fopen( "picnicTable.html", "w+");
	@fwrite ( $fs, $table."\r\n");
	@fclose ( $fs );
}

XML scripting with PHP

Just as PHP can write HTML pages, it can also write XML pages. It is necessary to specify the MIME type (called content-type in HTTP headers) for this to work properly. The first line of a *.php file that is scripting XML/XSLT must be as follows below. The remainder of the script would contain your markup and php mixed.

<?php
header('Content-Type: text/xml');
?>


PHP uses XSLT sorts

XSLT can sort and filter XML data files as described in the lesson on XSLT. This makes XML very well suited for placing data on Web pages. However the users view of the data is limited without server-side scripting because XSLT, like HTML, marks up static pages. Scripting introduces a manner of controlling XSLT for the purpose of user customization. Here is an example of an XSLT tag for starting an ascending sort on AUTHOR.

<xsl:for-each select='CATALOG/CD' order-by='+ AUTHOR'>

Here is the same XSLT tag written by PHP with a variable introduced to control the sort order and the data column.

<?php
$OrderBy = "- YEAR" // a descending sort on year
echo"<xsl:for-each select='CATALOG/CD' order-by='$OrderBy'>"
?>


XSLT customization

The example below is based on the same XML and XSLT file technology used in the CD catalog example from the lesson on XSLT where users are presented with a static table showing a CD Catalog. Both the XML and XSLT files must be converted to PHP files. Our PHP-script users will be able to change the order of the sort and the data field that controls sorting of the catalog.

Secure PHP programming



Security issues

Security issues, like bug issues, surface on a production site when there is too little planning during development. Prevent bugs by checking for division by zero, for the availablity of accurate/complete data, whether previous steps have been invoked, and so on protects your logic from abending due to out-of-range data or out-of-sequence processing. The same good sense helps your security thinking.

Introduction to secure PHP programming.

Mastery test