Code Breakdown 8

Most of the work we'll be doing, as you saw in the smaller version earlier in the chapter, has to do with what happens at our end of the connection. We want to always be able to deliver some kind of content to our Netsloth front door, even if it isn't always current up to the instant the user sees the page. If we were delivering stock quotations, for instance, we'd have to worry much more about that subject. But for news headlines particularly of the sort covered by a site like Slashdot, more...

session.cookie_domain (string)

Scope PHP_INI_ALL Default value empty The directive session.cookie_domain determines the domain for which the cookie is valid. This directive is a necessity because it prevents other domains from reading your cookies. The following example illustrates its use session.cookie_domain www.example.com If you'd like a session to be made available for site subdomains, say customers.example.com, intranet.example.com, and www2.example.com, set this directive like this session.cookie_domain .example.com

strtolower()

The strtolower function converts str to all lowercase letters, returning the modified string. Nonalphabetical characters are not affected. The following example uses strtolower to convert a URL to all lowercase letters url http WWW.EXAMPLE.COM echo strtolower url

Using PECL Filter

New in PHP 5 and quite promising is the Filter library of PECL code. Being developed by PHP's creator and other major contributors, the future of Filter looks bright, even though it's still in beta form at the time of this writing . The Filter package provides two types of security What Filter offers is a unified interface for performing common types of validation and sanitization. For example, I might commonly use code like this if isset _GET 'id' if is_numeric _GET 'id' id int _GET 'id' if id...

Testing with Mock Databases

Dynamic sites are all about databases. If you are testing them properly, you ought to test whether your code can actually modify a database. End-to-end tests do this for instance, if your test is whether you can log in with the correct username password combination, you are probably reading a database to do so. But testing whether you can update, create, and delete entries on a production database is a dangerous pastime, because it corrupts your real data Remember that CI allows you to declare...

Move Next and Move Last

Finally, create the Move Next and Move Last buttons in the same manner as the Move First and the Move Previous buttons, as shown in Listing 7-2. if this- gt currentpage this- gt totalpages-1 strnavigator . this- gt spannextinactive else strnavigator . 1, this- gt strnext if this- gt currentpage this- gt totalpages-1 strnavigator . this- gt lastinactivespan else strnavigator . -1, this- gt strlast _ Listing 7-2 Creating the Move Next and Move Last buttons

session.save_handler (files, mm, sqlite, user)

Scope PHP_INI_ALL Default value files The session.save_handler directive determines how the session information will be stored. This data can be stored in four ways within flat files files , within shared memory mm , using the SQLite database sqlite , or through user-defined functions user . Although the default setting, files, will suffice for many sites, keep in mind that the number of session-storage files could potentially run into the thousands, and even the hundreds of thousands over a...

strtoupper()

Just as you can convert a string to lowercase, you can convert it to uppercase. This is accomplished with the function strtoupper . Nonalphabetical characters are not affected. This example uses strtoupper to convert a string to all uppercase letters msg i annoy people by capitalizing e-mail text. echo strtoupper msg I ANNOY PEOPLE BY CAPITALIZING E-MAIL TEXT.

SOAP Client and Server Interaction

Now that you're familiar with the basic premises of using this extension to create both SOAP clients and servers, this section presents an example that simultaneously demonstrates both concepts. This SOAP service retrieves a famous quote from a particular boxer, and that boxer's last name is requested using the exposed getQuote method. It's based on the boxing.wsdl file shown in Listing 20-12. Let's start with the server. The boxing server is simple but practical. Extending this to connect to a...

Installing PHP's CrackLib Extension

To use the CrackLib extension, you need to first download and install the CrackLib library, available at http www.crypticide.org users alecm . If you're running a Linux Unix variant, it might already be installed, because CrackLib is often packaged with these operating systems. Complete installation instructions are available in the README file found in the CrackLib tar package. PHP's CrackLib extension was unbundled from PHP as of version 5.0.0, and moved to the PHP Extension Community Library...

Generating a WSDL Document

You'll need to generate a Web Services Definition Language WSDL document in order to offer clients the opportunity to call methods via a proxy as was demonstrated in Listing 20-7. Doing so via NuSOAP is surprisingly easy, accomplished with few modifications to the servers demonstrated thus far. Two additional methods must be called to initiate WSDL configuration and specify the WSDL namespace configureWSDL and schemaTargetNamespace , respectively. In addition, because PHP is a loosely typed...

truncate

The truncate junction truncates a variable string to a designated number of characters. Although the default is 80 characters, you can change it by supplying an input parameter demonstrated in the example . You can optionally specify a string that will be appended to the end of the newly truncated string, such as an ellipsis . In addition, you can specify whether the truncation should occur immediately at the designated character limit, or whether a word boundary should be taken into account...

oci_error()

This function returns an associative array of error messages generated by the last OCI8 function, or returns an empty array if no error occurred. Here is the syntax If the optional source parameter is included, the most recently occurring error emanating from that identifier will be used. Do not provide the source parameter for oci_connect errors. In Listing 32-1, we showed you a simple example of error handling for the oci_connect call print 'Oracle connect error ' . errmsg 'message' We assign...

oci_fetch_all()

As the name implies, oci_fetch_all retrieves all the rows from a database query at once here is the syntax int oci_fetch_all resource statement, array amp output , int skip , int maxrows , int flags This form of oci_fetch_ can be useful in an environment where you have enough memory to hold the entire results of the query and you need to have the entire result set available before you can perform an aggregate operation for your users, for example. The optional parameters skip and maxrows define...

Stopping the Loop

Stopping the loop is a simple matter of calling Gtk main_quit, but deciding how to call it is not quite as simple. While the call to Gtk main is usually done automatically when the script is run, the call to exit the loop is normally done in reaction to a user event. Automatically shutting down the application probably isn't the best idea, so most applications usually wait for the user to close the window or select an exit option from a menu. Since shutting down an application is normally...

Paginating Large Result Sets

In previous sections of this chapter, you've seen how to massage and reformat individual records so they meet your display requirements. In this concluding segment, it's time to step back and understand how to better present the entire set of records returned by an SQL query. It's not uncommon for query result sets to contain hundreds or even thousands of records. In such cases, it's usually not user friendly to display the entire result set on a single HTML page, as doing so forces the user to...

substr_count()

int substr_count string str, string substring The substr_count function returns the number of times substring occurs in str. The following example determines the number of times an IT consultant uses various buzzwords in his presentation buzzwords array mindshare, synergy, space talk lt lt lt talk I'm certain that we could dominate mindshare in this space with our new product, establishing a true synergy between the marketing and product development teams. We'll own this space in three months....

Handling File Uploads

Okay, we can now juggle files we've created ourselves, but the next piece of the puzzle is to accept files uploaded by visitors to your site, and handle them just as deftly. We'll start with the basics let's write an HTML form that allows users to upload files. HTML makes this quite easy with its input type file tag. By default, however, only the name of the file selected by the user is sent. To have the file itself submitted with the form data, we need to add enctype multipart form-data to the...

css( path[mixed], rel[string], attributes[array], inline[bool] )

path The name of the style sheet excluding the .css extension or an array of multiple style sheets in the app webroot css directory. rel 'stylesheet' The rel attribute if set to import, then the function will return the import link in the lt style gt tags rather than the lt link rel 'stylesheet' gt tag. attributes Contains any HTML attributes to be included in the lt link gt or lt style gt tag arranged as keys named for the attribute and values to be assigned to the attribute. inline true If...

lastval

The lastval function, new in PostgreSQL 8.1, operates similarly to currval, except that instead of explicitly stating the sequence to be called against, lastval automatically returns the value of the last sequence nextval was called against This makes it a little easier to manipulate tables, because you can insert into a table and retrieve the generated serial key value without having to know the name of the sequence. Like currval, calling lastval in a session where nextval has not been called...

setResource()

Sets a PHP resource handle as the source for the download. Once the download has been sent, the handle to the resource will be closed. If handle doesn't refer to a valid resource, which is determined by the PHP method is_resource , the method will return PEAR_Error. mixed setResource integer resource null resource integer The resource handle to the data to send as the download. Set this to null to clear the resource from the download.

Using Arrays with Forms

Arrays are particularly potent when used in combination with form elements that support more than one value, such as multiple-selection list boxes or grouped checkboxes. To capture a user's input in an array, simply add square braces to the form element's ' name' to automatically convert it into a PHP array when the form is submitted. The easiest way to illustrate this is with an example. Consider the following form, which holds a multiple-selection list of popular music artists lt form method...

oci_fetch_array()

The oci_fetch_array function retrieves each row of the statement as an associative array, a numerically indexed array, or both. Here is the syntax array oci_fetch_array resource statement ,int result_type By default, it retrieves both arrays you can modify this default behavior by passing one of the following values in as the result_type OCI_ASSOC Returns the row as an associative array, with the key represented by the field name and the value by the field contents. Using this option is...

Practical Session-Handling Examples

Now that you're familiar with the basic functions that make session handling work, you are ready to consider a few real-world examples. The first example shows you how to create a mechanism that automatically authenticates returning registered site users. The second example demonstrates how you can use session variables to provide the user with an index of recently viewed documents. Both examples are fairly commonplace, which should not come as a surprise given their obvious utility. What may...

Writing an .htaccess File

This example demonstrates writing an . htaccess file using the File_HtAccess class. Here, all the major options are specified ahead of time in the options array and passed to the class's constructor. However, you can also set each of these options using the appropriate accessor functions. For example, you can use the setAuthType function to set the AuthType directive the option authtype in the options array . Writing an .htaccess file require_once 'File HtAccess.php' create a new .htaccess file...

Sanitize

The Sanitize utility contains functions designed for cleaning up data and text. Stripping white-space, HTML tags, and references to scripts and style sheets, as well as escaping text for SQL, can be accomplished with the Sanitize utility. Remember to instantiate the Sanitize utility first with App import and assign the utility as a class object for use in the controller or model App import 'Core','Sanitize' sanitize amp new Sanitize Sanitize can strip out HTML tags from a block of text by using...

Parsing the XML File

Before the DataSource parses the XML file, let's give it something with which to work. Paste something like the contents of Listing 14-8 into the app webroot files data.xml file. Notice that Listing 14-8 is formatted as XML 1.0 standard tags named after fields in the current posts table in the database. Listing 14-8. Contents to be Added to the data.xml File lt xml version 1.0 encoding UTF-8 gt lt blog gt lt post gt lt name gt Writing Posts in XML is a Snap lt name gt lt date gt 2008-11-08 12...

Developing the Storeltem class

The first portion of code to focus on will be the individual product items that will be displayed to the left of the shopping cart. The store items MovieClip will be dynamically added to the Stage and will be assigned to a custom class Storeltem. The class is responsible for assigning the store item variables and displaying the necessary values. Just like the class chapter, these classes are built up of stand-alone packages for simplicity, so there is no need to provide a package structure. The...

Validating Form Input 2

Now that you know the basics of input sanitization and validation, let's apply this learning to a practical project. This next example presents a Web form that asks users to enter various details for a book the title, author, ISBN number, and price. It then validates this data using a mix of the techniques discussed in previous sections and, once validated, saves it to an SQLite database. To begin, create an SQLite database and table to store the records entered by the user Enter .help for...

IP-based Authentication

Sometimes you need an even greater level of access restriction to ensure the validity of the user. Of course, a username password combination is not foolproof this information can be given to someone else, or stolen from a user. It could also be guessed through deduction or brute force, particularly if the user chooses a poor login combination, which is still quite common. To combat this, one effective way to further enforce authentication validity is to require not only a valid username...

Creating Destructors

The corollary to the constructor is the destructor. Whereas a constructor is automatically invoked when an object is created, the destructor is called when the object is destroyed. This may occur when you overtly remove the object obj new ClassName unset obj Or this may occur when a script ends at which point PHP releases the memory used by variables . Being the smart reader that you are, you have probably already assumed that the destructor is created like so class ClassName function...

Aggregate Classes

An aggregate class is any class that includes a data member that is itself an object. Let's quickly create a Team class as an example. This class has as a data member, an array of objects called players. The class definitions for the Player class and the Team class are shown in Listing 13-5. public function getName return this- gt name public function setPosition position this- gt position position private players array private name public function __construct name this- gt name name public...

Traversing the Result Set

All that remains before displaying your page navigator is to traverse the result and output it. echo lt div while row rs- gt getRow echo row 0 . - . row 1 echo lt br gt n echo lt br gt echo lt div gt n The getRow method of a MySQLResultSet calls the PHP function mysql_fetch_array, retrieving the current record and moving the record pointer forward to the next record. This is a perfectly adequate way of iterating through your results, but you will develop a different approach in Chapter 10....

Entities and attributes

At a basic level of a data model are entities objects that you are interested in as part of the data model you are creating. For example, if you were making an online store, you would want to know the customer's name. Steve Suehring is an example of an entity. The specific name, Steve Suehring, is the entity. For a successful online store, you probably want more than one customer. Therefore you should abstract the entity into a general entity type. For this example, the entity type would be...

Class Inheritance

As applied to PHP, class inheritance is accomplished by using the extends keyword. Listing 7-3 demonstrates this ability, first creating an Employee class, and then creating an Executive class that inherits from Employee. Note A class that inherits from another class is known as a child class, or a subclass. The class from which the child class inherits is known as the parent, or base class. Listing 7-3. Inheriting from a Base Class lt php Define a base Employee class class Employee Define a...

Chapter 5 Self Test

1. State one advantage of using functions. 2. What is the difference between an argument and a return value 3. Using the relationship DISTANCE SPEED TIME, write a function that calculates distance given the speed and time. Use this function to find the distance traveled by an aircraft departing from London, England, at 9 30 p.m. and arriving in Bombay, India, at 11 a.m. the next day. Assume the aircraft flies at 910 km hr and the time difference between London and Bombay is 4.5 hours. 4. Using...

Example 12-7. Sending all submitted form parameters to the error log with

Capture output instead of printing it ob start Call var dump as usual var_dump _POST Store in output the output generated since calling ob start output ob get contents Go back to regular printing of output ob end clean The ob_start , ob_get_contents , and ob_end_clean functions in Example 12-7 manipulate how the PHP interpreter generates output. The ob_start function tells the interpreter Don't print anything from now on. Just accumulate anything you would print in an internal buffer. When...

Setting Cookies

In PHP, cookies are set with the setcookie function, which accepts six arguments the cookie name, its value, its expiry date in UNIX timestamp format , its path and domain, and a Boolean flag indicating its security status. Only the first argument is required, all the rest are optional. To better understand this, try out the following example script lt php 6 set a cookie called 'username' with value 'admin' expiring after 1 day setcookie 'username', 'admin', mkti me 86400, ' ' gt The setcookie...

To add tasks to the database:

1. Begin a new PHP script in your text editor or IDE, starting with the HTML Script 1.2 . lt DOCTYPE html PUBLIC - W3C DTD XHTML 1.0 Transitional EN http www.w3.org TR xhtml1 DTD xhtml1-transitional.dtd gt lt html xmlns http www.w3.org 1999 xhtml xml lang en lang en gt lt meta http-equiv content-type content text html charset iso-8859-1 gt lt title gt Add a Task lt title gt lt head gt lt body gt lt php Script 1.2 - add_task.php Script 1.2 Tasks are added to the database using this script. Tasks...

Using the switch Structure to Simplify Programming

The situation in the Binary Dice program happens often enough that another structure is designed for when you are comparing one variable to a number of possible values. The Switch Dice program in Figure 3.9 looks identical to the Binary Dice program as far as the user is concerned, except Switch Dice shows the roll's Roman numeral representation. This version shows a die roll in Roman numerals. This version shows a die roll in Roman numerals. While the outward appearance of the last two...

Using Smarty

To use Smarty, you just need to make it available to the executing script, typically by way of the require statement With that complete, you can then instantiate the Smarty class That's all you need to do to begin taking advantage of its features. Let's begin with a simple example. Listing 19-3 presents a simple design template. Note that there are two variables found in the template title and name. Both are enclosed within curly brackets, which are Smarty's default delimiters. These delimiters...

mysql_unbuffered_query

mysql_unbuffered_query query , link_id , result_mode This function sends an SQL query to MySQL, without fetching or buffering the result rows automatically, as mysql_query and mysql_db_query do. This method has two advantages PHP does not need to allocate a large memory buffer to store the entire result set, and you can begin to process the results as soon as PHP receives the first row, instead of having to wait for the full result set to be received. The downside is that functions that require...

pg_result_error_field()

string pg_result_error_field resource result, int fieldcode Only available when used in conjunction with PostgreSQL 7.4 and later, the pg_result_error_field function returns error information pertinent to the resource specified by result. The returned error information is specific to the value defined by fieldcode. Twelve fieldcode values are supported, including PGSQL_DIAG_CONTEXT Contains a trace of internally generated information pertinent to the error. Available as of PostgreSQL version...

Application Builder

As the name implies, the Application Builder makes it easy for your developers to create Web-enabled applications that use the database for the application's data. Clicking the down arrow next to the Application Builder icon gives you access to three sample applications that cover most of the key features available with Application Builder. The entire Oracle Database XE Web application environment is an Application Builder application. Note The Application Builder icon shows up for all users...

Authentication with PEAR Auth

One of the more common elements in today's Web sites is an authentication system users register with a site, they log in to gain access to some parts, and restricted pages allow or deny access accordingly. Such systems aren't hard to implement I've done so in some of my other books but here I'd like to look at what PEAR has to offer. The PEAR Auth package provides a really easy, yet customizable authentication system. To show it off, I'll start with one very simple example. This will mostly...

fsockopen()

resource fsockopen string target, int port , int errno , string errstring , float timeout The fsockopen function establishes a connection to the resource designated by target on port port, returning error information to the optional parameters errno and errstring. The optional parameter timeout sets a time limit, in seconds, on how long the function will attempt to establish the connection before failing. The first example shows how to establish a port 80 connection to www.example.com using...

Sending Mail with Inline Images

In this example, you'll use the Mail_MIME class to send an e-mail message that contains inline images that will display in a mail client that can display HTML content. The great thing about sending this kind of mail is that you can send an alternate text component that's displayed to people who cannot view HTML. As you'll see, the Mail_MIME class doesn't send the mail itself it's only used to construct the mail message that you then send using the standard Mail class. require_once 'Mail.php'...

Merging Forms and Their Result Pages with Conditional Statements

Normally, when creating and processing forms in PHP, you would place the HTML form in one file, and handle form processing through a separate PHP script. That's the way all the examples you've seen so far have worked. However, with the power of conditional statements at your disposal, you can combine both pages into one. To do this, assign a name to the form's submit control, and then check whether the special _POST container variable contains that name when the script first loads up. If it...

Project 7-2: Adding Employees to a Database Add New Employee

Figure 7-7 A Web page displaying the list of employees single library file. It's also significantly smaller in size than MySQL the command-line version of SQLite weighs in at under 200KB and supports all the standard SQL commands you're used to. MySQL and SQLite also differ in their licensing policies unlike MySQL, SQLite source code is completely public-domain, which means that developers can use and distribute it however they choose, in both commercial and noncommercial products. SQLite's...

Invoking Unrelated Constructors

You can invoke class constructors that don't have any relation to the instantiated object simply by prefacing_constructor with the class name, like so As an example, assume that the Manager and Employee classes used in the previous example bear no hierarchical relationship instead, they are simply two classes located within the same library. The Employee constructor could still be invoked within Manager's constructor, like this Calling the Employee constructor like this results in the same...