Developer

Understanding functions and classes in PHP

PHP is continuing to grow in popularity. This article continues our look at PHP by exploring the use of functions and classes in the language. Learn from examples that display forms, log information, and send e-mail notices.


PHP (PHP Hypertext Preprocessor) is an inline programming language designed for use with Web functionality. In "Tutorial: Getting started with PHP," we covered syntax basics and discussed how to use PHP for in-line coding. This article picks up where we left off: introducing classes and taking a more detailed look at the use of functions in the PHP language.

Where is PHP today?
In April 2001, PHP.net reported Netcraft's findings of PHP usage on 5.7 million Web sites worldwide. Its numbers for May were almost 6.3 million sites, an increase of over 9 percent. In Minneapolis, several IT shops, including the well-established custom development provider Bitstream Underground, have moved into PHP. The language continues to grow in popularity and has proved itself easy to learn and use by more and more companies worldwide.

Sample Web form
For this discussion, we will be walking through a PHP script that does the following:
  • Displays a Web form page
  • Logs submitted information
  • Sends the site administrator an e-mail notice
  • Displays the log

The name of our script is register.php, and it’s set up to demonstrate the use of classes. As with the favorite.php script from our previous article, the code below could exist within an HTML page. In fact, it really does—but the first thing we've done on this page is escape out of the HTML using the “php ear tag.” This allows us to call the script directly from a browser or call the class from another script in a larger application without sending the HTML header information.

Line numbers are included for reference purposes only and should not be included in your code. Also note that this script uses PHP 4 syntax. If you'd like to see the script in action, I have it posted here.
 
1   <?php
2
3   //   Example Web form
4   //   http://www.shelleydoll.com/shelley/test/register.php
5   //   version 1.2
6

To make the script work, we have to invoke the class. We’ll see how to do this from other scripts in a future article, but for now, we'll make register.php self contained:

 
7   $registration = new WebForm;

This line does a number of things:
  • It declares a variable, $registration.
  • The PHP function new sets the variable type to class.
  • The class, WebForm (line 9, below), serves as a template for the resulting object.
  • WebForm's functions are loaded into the object, resulting in methods.
  • The initializing method for the object is executed.
  • The instance of the WebForm class is assigned to the object, $registration.

Defining and initializing a class
Next, we begin defining our class. The first thing to do is declare variables that function within the scope of the class object. These can then be referenced from all methods contained in the object. In PHP 3, these variables were referred to as global variables. In PHP 4, they are distinguished from global variables and are called var variables.
 
8
9   class WebForm {
10
11      var $debug;
12      var $logfile;
13      var $fwd_page;
14      var $mailto;
15      var $mailfrom;
16      var $server_id;
17      var $FORM;
18
19   #########################################################

Now, we define our initializing method. Note that this method must have the same name as the class that was called, in order to be executed when the class instance is created.
 
20
21      function WebForm() {
22         global $HTTP_POST_VARS;
23
24         #——————————————————————————————-
25         #       EDITABLE CONFIGURATION VARIABLES
26         $this->debug = 0;                      # debug level:  0=off, 1=on
27         $this->logfile = "./email_log.txt";    # log file, in relation to this script
28         $this->fwd_page = "./email_log.txt";   # location to send user after submiting the form
29         $this->mailto = "admin@company.com";         # who the notification email gets sent to
30         $this->mailfrom = "nobody@company.com";      # 'From' field in email message
31         $this->server_id = "company.com";              # Server identification - displays in text of email
32         #——————————————————————————————-
33
34         if ($this->debug != 0) { echo "Debug level ".$this->debug."\n"; }
35
36         $this->FORM = $HTTP_POST_VARS;
37

Notice the syntax used on lines 26 through 31 to reference the var variables that we declared earlier: $this->debug (it reads as my object, debug). The values defined within a method in this way are preserved throughout the class object and may be referenced later from other methods. This makes initializing configuration variables, such as those in our example, easy to administer.

After defining the variables, we have a debug statement on line 34 for use when modifying the code, along with the assignment of expected Web form data to the var variable, $this->FORM.

$HTTP_POST_VARSis a PHP global associative array variable, defined in the track_vars standard installation directive. $HTTP_POST_VARS returns an array of data from an HTML POST command, so $this->FORM is also an array.
 
38         if ($this->FORM[submit] == "Register") {

Here, we’re basically saying, "If my object, FORM, has an array key of submit with a value of Register... (i.e., If someone clicked the Submit button on the form...), then…”
 
39            $email = $this->FORM[email];

"...assign the e-mail address that was entered to a local variable…"
 
40            if (eregi ("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$",$email)) {

"…and if the extended regular expressions engine (ereg) finds the appropriate characters in that local variable, then..."
 
41               $this->send_email($email);

"...call the method in my object named send_email, with the parameter $email."
 
42           } else {

"Otherwise, if ereg doesn't find the appropriate characters, then..."
 
43            $email = "localhost";
44            $this->send_email($email);
45            }

"…change the value of the local variable $email and call the send_email method."
 
46         } else {
47            $this->show_page("form");
48         }

"Otherwise, if the Submit button wasn't clicked, then tell the method show_page to display the form."
 
49      }

End of initialization function.

The show_page function
The show_page function is called in line 47 during initialization and later from the send_email function (line 130). Its purpose is to return the requested type of Web page. Not all functions must receive parameters, but show_page expects a value for ($page_type) when called.
 
50
51      #########################################################
52
53      function show_page($page_type) {
54         global $SCRIPT_NAME;

The function begins by declaring the global variables it will use. Next, depending on the value the function received, it will either return HTML (line 57) or the location of an HTML header (line 82).
 
55         switch($page_type) {
56            case "form"  :    
57               print <<<EOF
58              <html>
59               <head><title>User Registration Web Form: $page_type</title></head>
60               <body bgcolor="#FFFFFF">
61               <form action="$SCRIPT_NAME" method=POST>
62               <b>User Registration Web Form</b><br><br>
63               <table border=0>
64               <tr><td>Name</td><td><input type=text name=name value="Jane Doe"></td></tr>
65               <tr><td>Address</td><td><input type=text name=street1 value="123 PHP Lane"><br>
66               <input type=text name=street2 value="Apt. 456"></td></tr>
67               <tr><td>City</td><td><input type=text name=city value="Minneapolis"></td></tr>
68               <tr><td>State</td><td><input type=text name=state value="MN"></td></tr>
69               <tr><td>Zip</td><td><input type=text name=zip value="12345"></td></tr>
70               <tr><td>Email</td><td><input type=text name=email value="jdoe@hotmail.com"></td></tr>
71               <tr><td>Day Phone</td><td><input type=text name=dayphone value="123.123.1234"></td></tr>
72               <tr><td>Alternate Phone</td><td><input type=text name=altphone value="456.456.4567"></td></tr>
73               <tr><td>Best time to be reached</td><td><input type=text name=besttime value="never"></td></tr>
74              <tr><td>Special requests</td><td><input type=text name=requests value="world peace"></td></tr>
75               <tr><td>Comments</td><td><input type=text name=comments value="nice script!"></td></tr>
76               <tr><td><input type=submit name=submit value="Register"></td><td> </td></tr>
77               </table>
78               </form></body></html>
79      EOF;
80               break;
81            case $this->fwd_page       :     
82               header("Location: ".$this->fwd_page);
83              break;
84         }
85      }
86

A few things worth noting about the show_page example:
  • $SCRIPT_NAME, on lines 54 and 61, is a PHP global variable, similar to $HTTP_POST_VARS, which returns the name of the script currently being run.
  • There are several possible ways to display HTML—one of which is a print statement, as on line 57. You could also use echo, if you escape quotation marks with a backslash (\), or even escape back into HTML using ?>.
  • When using an end-of-file marker with the print statement, the marker must be at the beginning of a new line (line 79).
  • On line 56, the word form is literally expected, so it appears in quotation marks. Conversely, the statement on line 81 will be evaluated.
  • On line 82, the period between “Location: “ and $this->fwd_page allows the latter to be evaluated then appended to the former. This holds true for all PHP syntax, including variable definition, echo statements, etc.

The send_email function
If the user has submitted the form, the send_email function is called in lines 41 and 44. It formats and sends out e-mail and then calls the function write_log to log the activity and show_page to redirect the user's browser. The send_email function expects a value for ($addr) when called.
 
87     #########################################################
88
89      function send_email($addr) {
90
91         if ($this->debug == 1) { echo "valid email: ".$addr."\n\n"; }
92
93         switch ($addr) {
94            case "localhost"   :
95              $error_msg = "<br><br><b>Warning:
96                  The above request contains an invalid email address.</b>";
97               if ($this->debug == 1) { $error_msg .= "Debugging send_email"; }
98            case $this->FORM[email] :
99               if ($debug) { echo "send_email: addr = ".$this->FORM[email]; }
100               $to = $this->mailto;
101               $from = "From: ".$this->mailfrom;
102               $subject = "User Registration";
103               $message = "<HTML><BODY BGCOLOR\=#FFFFFF>
104                  A new user has registered.<BR><BR>
105                  Name:  ".$this->FORM[name]."<BR>
106                  Address: <blockquote>".$this->FORM[street1]."<BR>".$this->FORM[street2]."<br>"
107                  .$this->FORM[city].", ".$this->FORM[state]." ".$this->FORM[zip]."</blockquote>
108                  Email:  ".$this->FORM[email]."<BR>
109                  Daytime Phone:  ".$this->FORM[dayphone]."<BR>
110                  Other Phone:  ".$this->FORM[altphone]."<BR>
111                 Best Time to be reached: ".$this->FORM[besttime]."<br>
112                  <br><br>
113                  This individual included the following requests: ".$this->FORM[requests]."
114                  <br><br>Comments:  ".$this->FORM[comments]."<BR><BR>
115                  <BR><BR>";
116
117               if (isset($error_msg)) { $message .= $error_msg; }
118               $message .= "<br><br>This message was generated automatically by ".$this->server_id.".<BR>
119              </BODY></HTML>";
120            break;
121         }
122
123         if ($debug == 1) { echo $message; }
124
125         if (!(imap_mail($to, $subject, $message, $from))) {
126            $addr = "Mail not sent";
127         }
128
129         $this->write_log($addr);
130         $this->show_page($this->fwd_page);
131      }
132

Lines 94–121 show a clever use of the case statement. Notice there is no break; statement to end the first case. This means that when the first case is met, a variable is written (line 95), then the logic continues to flow through the switch until it does hit a break; at the end of the second case (line 120).

It is definitely worth checking out both the imap function and the mail function documentation in the online manual for an explanation of parameters.

The write_log function
The write_log function is called every time a registration form is processed, and it’s called from within the send_email function on line 129. It writes several items to a log file on the local file system: a date stamp, the user-entered information, and an indication of whether an e-mail was sent to the site administrator ($sent_from). The write_log function expects a parameter of ($sent_from).
 
133      #########################################################
134      function write_log($sent_from) {
135
136         $FILE = fopen("$this->logfile", "a");

$FILE is our filehandler. The fopen function opens the file $this->logfile for appended writing. For an explanation of the fopen function parameters, see the online documentation.
 
137         $log .= date("HisYmd").",";

This line writes the date in the prescribed format, followed by a comma, to the local variable $log. Notice we use.= (append) instead of = (is set to), so we don’t overwrite existing data in the variable.
 
138         foreach ($this->FORM as $value) {
139            $log .= $value.",";
140         }

The foreach statement here steps through each value in the array $this->FORM and writes it to the $log variable followed by a comma.
 
141         $log .= $sent_from."\n";

$sent_from is appended to the $log variable, followed by a carriage return. (\n)
 
142         fwrite($FILE,$log);
143         fclose($FILE);
144
145      }

Finally, the value of $log is written to the file handler, and the file is closed.

The only thing remaining is to end the script and escape back into HTML:
 
146   }
147   ?>

Additional PHP resources
Web sites: Builder articles:

Summary
Working through the Web form example, we learned how to use a class and how to define and call functions. Additionally, we looked at methods for displaying HTML, sending e-mail, and writing to the local file system. As if that weren't enough, we also dealt extensively with object and variable handling.

If you made it this far—good job! If you need more information, the Classes and Objects section of the PHP online manual has been updated and contains some useful tips. When referencing the manual, always be sure to read the user comments. They often include examples of usage and other helpful information.

Next time, we'll use what we've learned so far and take it one step further: We'll look at using a database to create dynamic content. If you have questions or requests in the meantime, feel free to post a message below.

 

Editor's Picks

Free Newsletters, In your Inbox