Secure PHP Programming

Vny Web server can be thought of as a castle under constant attack by a sea of barbarians. And, as the history of both conventional and information warfare shows, often the attackers' victory isn't entirely dependent upon their degree of skill or cunning, but rather on an oversight by the defenders. As keepers of the electronic kingdom, you're faced with no shortage of potential ingresses from which havoc can be wrought, perhaps most notably User input Exploiting disregarded user input is...

Problems with the CI 'Super-Object'

There was one big problem for Rick Ellis when he wrote the original code. PHP 4 handles objects less elegantly than PHP 5, so he had to introduce a 'really ugly hack' (his words) into the Base4 file. Ugly or not, the hack works, and so we don't need to worry about it. It just means that CI works as well on PHP 4 systems as it does on PHP 5. There are two other issues worth mentioning here You can find yourself trying to work with an object that isn't available. You have to structure your site...

Entering the Server View

The Server view can be accessed from the Home page by choosing one of the following links Show MySQL runtime information Show MySQL system variables The Privileges link is visible only if we are logged in as a privileged user. When in the Server view, we see a menu to go to the other server-related sub-pages. The Privileges sub-page in the Server view contains dialogs to manage MySQL user accounts, and their privileges on global, database, and table levels. This sub-page is centered on the user...

Safe_mode_protected_env_vars (string)

Scope PHP_INI_SYSTEM Default value LD_LIBRARY_PATH This directive protects certain environment variables from being changed with the putenv() function. By default, the variable LD_LIBRARY_PATH is protected, because of the unintended consequences that may arise if this is changed at run time. Consult your search engine or Linux manual for more information about this environment variable. Note that any variables declared in this section will override anything declared by the...

Canonicalization Method Element

The CanonicalizationMethod element defines the type of canonicalization that must be applied to the SignedInfo element when processing a digital signature. Implementations must at least support canonical XML without comments, as noted by the value http www.w3.org TR 2001 REC-xml-c14n-20010315. Other possible values include, but are not limited to, http www.w3.org which is canonical XML with comments, and http www.w3.org TR xml-exc-c14n , which is exclusive canonical XML. As shown in Listing...

Adding and Changing Comments

The code for working with comments is nearly identical to the PHP code for modifying posts. This is because posts and comments are considered the same thing in your code. There isn't much difference between them. The changes are emphasized in Example 17-16. Figure 17-8. The update was successful Figure 17-8. The update was successful File Edit View History Bookmarks Tools Help PHP Version 12, to be released third quarter 2020. Featuring the artificial intelligence engine that writes the code...

Node Type

In many cases when using the DOM extension, a node will be returned but you won't know what type of node it is. In these instances, you can check the type of node using the nodeType property. This property returns an integer corresponding to one of the built-in constants for node types type root-> nodeType print type This code prints the number 1, which corresponds to the XML_ELEMENT_NODE constant. You can find the complete list of node type constants in Appendix B, and in a moment you will...

Creating and Retrieving a Cart

Unless you have an existing cart, which must have been accessed within the past 90 days, you will need to create a new shopping cart. To do this, you must add at least one item to the cart during its creation. Items are referenced by an Amazon Standard Item Number (ASIN). You can find these numbers within the product Web pages as well as within the results from other searches. If you look at one of the items in Listing 17-8, you will notice that each item has an ASIN element. For instance, the...

Creating a Personal To-Do List

Now that you've got a handle on SQLite, how about using it in a practical application a personal to-do list that you can update and view through your Web browser. This to-do list will allow you to enter tasks and due dates, assign priorities to tasks, edit task descriptions, and mark tasks as complete. It's a little more complicated than applications you've worked on so far, as it includes quite a few moving parts however, if you've been following along until this point, you shouldn't find it...

User-Derived Types

So far, you have seen how to use some built-in simple types. XML Schemas are extensible, which allows you to define your own data types by deriving a type from a simple type. Take, for example, the declaration for the credits element in Listing 3-26. It is a decimal data type, so the values it can take are pretty much endless. Say you want to limit the possible values to 0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, and 4. You can't use a built-in type directly, so you must create your own that will be...

Table 18-1. fopen( ) file modes

On non-POSIX systems, such as Windows, you need to add a b to the mode when opening a binary file, or reads and writes get tripped up on NUL (ASCII 0) characters fh fopen(,c images logo.gif,,,rb') To operate on a file, pass the file handle returned from fopen( ) to other I O functions such as fgets( ), fputs( ), and fclose( ). If the file given to fopen( ) doesn't have a pathname, the file is opened in the directory of the running script (web context) or in the current directory (command-line...

To validate a form:

Begin a new PHP script in your text editor or IDE, starting with the HTML (Script 4.1). < DOCTYPE html PUBLIC - W3C DTD XHTML 1.0 Transitional EN http www.w3.org TR xhtml1 DTD xhtml1-transitional.dtd> < html xmlns http www.w3.org 1999 xhtml xml lang en lang en> < meta http-equiv content-type content text html charset iso-8859-1 > < title> Registration Form< title> < head> < body> < php Script 4.1 - register.php Script 4.1 This page both displays a registration form...

Subnet Converter

You've probably at one time scratched your head trying to figure out some obscure network configuration issue. Most commonly, the culprit for such woes seems to center on a faulty or unplugged network cable. Perhaps the second most common problem one faces is a mistake made when calculating the necessary basic network ingredients IP addressing, subnet mask, broadcast address, network address, and the like. To remedy this, a few PHP functions and bitwise operations can be coaxed into doing the...

Preg_replace()

Mixed preg_replace (mixed pattern, mixed replacement, mixed str , int limit ) The preg_replace() function operates identically to ereg_replace(), except that it uses a Perl-based regular expression syntax, replacing all occurrences of pattern with replacement, and returning the modified result. The optional input parameter limit specifies how many matches should take place. Failing to set limit or setting it to -1 will result in the replacement of all occurrences. Consider an example text This...

Ldap_get_entries()

Array ldap_get_entries (resource link_id, resource result_id) The ldap_get_entries() function offers an easy way to place all members of the result set into a multidimensional array. The following list offers the numerous items of information that can be derived from this array The total number of retrieved entries The DN of the nth entry in the result set The total number of attributes available in the nth entry of the result set The number of items associated with the nth entry of attribute...

Calendar Popup

As an added benefit, phpMyAdmin offers a calendar popup for easy data entry. We will start by adding a DATE field, date_published, to our books table. If we go into Insert mode, we should now see the new field where we could type a date. A Calendar icon is also available This icon brings a popup, synchronized to this DATE field if there is already a value in the field, the popup displays accordingly. In our case, there is no value in the field, so the calendar shows the current date Small...

Installing the Linux Client

Navigate to the Oracle Web site download area for Oracle Database XE, http www.oracle.com and follow the links to download the Linux version of Oracle Database XE. Registration for OTN is required but free and gives you access to many other resources on http otn.oracle.com. The Linux version will run fine on the distributions mentioned in Chapter 26. The installation may work on other Linux distributions, but proceed at your own risk. There are two installation files available,...

How It Works

All right, so you have had a good look at the code and witnessed what the end result looks like. Now let's take some time to understand how it works. The main file to have a look at is the sample7_l.php file. This file is the wrapper that holds the rest of the code in place, and it's where you would go in order to use the gallery. Let's have a look. < DOCTYPE html PUBLIC - W3C DTD XHTML 1.0 Transitional EN < html < head> < link rel stylesheet type text css href style.css > <...

Aggregating RSS Feeds Using XSL

This example demonstrates how to use the XSL extensions and some of the XSLT functionality using RSS for the source data, since it is a data source everyone should be able to access. I will not explain the structure and workings of RSS (covered in detail in Chapter 14) in this example because the focus is on using the extension and XSLT functionality. This example will show how to combine a couple of the PHP news feeds into a single XML data source and store them locally. The feed to be...

Global and Local Scope

When using a DTD, the root element is declared in the DOCTYPE declaration to specify the starting element of the document. XML Schemas do not have this concept. Schemas have the concept of global and local scope. All definitions and declarations, which are direct child elements of the schema element, are in the global scope. Elements in this respect refer to XML elements in general and not to xsd elements. The rest of the declarations and definitions are local to whichever element contains...

Linked-Tables Infrastructure

The relational system's infrastructure is stored in tables that follow a predetermined structure. The data in these tables is generated and maintained by phpMyAdmin on the basis of our actions from the interface. There are two possible places to store these tables In a user's database. Thus every web developer owning a database can benefit from these features. In a dedicated database, which we call pmadb (phpMyAdmin database). In a multi-user installation (discussed later), this database may be...

Adding and Removing Widgets

Containers and widgets have some handy methods to help you move widgets into and out of containers. Some are specialized for the container type, and we will cover those in later chapters. For now, we will look at the methods that come with the base GtkContainer, GtkBin, and GtkWidget classes. The add, remove, and reparent Methods You have already seen one of the methods for adding a child in some of the previous examples. The appropriately named add method will take a widget and make it a child...

Inclusive Namespaces Prefix List

The InclusiveNamespaces PrefixList throws a little curve to the rules already defined for handling namespace nodes. A namespace node matching a prefix or token in the list is rendered according to the rules of canonical XML rather than those of exclusive XML canonicalization. Namespace nodes in the node set that match a prefix or token in the list, unlike those not in the list, do not need to have parent elements in the node set. This can make your output look a little strange because it can...

Configuring Apache for PHP

You must configure Apache to recognize and run PHP files. An Apache configuration file, httpd.conf, is on your system, possibly in etc or in usr local apache conf. You must edit this file before PHP can run properly. Follow these steps to configure your system for PHP 1. Open the httpd.conf file so you can make changes. 2. Configure Apache to load the PHP module. Find the list of LoadModule statements. Look for the following line LoadModule php6_module libexec libphp6.so If this line isn't...

Ldap_first_attribute()

String ldap_first_attribute (resource link_id, resource result_entry_id, The ldap_first_attribute() function operates much like ldap_first_entry(), except that it is intended to retrieve the first attribute of the result entry, denoted by result_entry_id. One point of confusion regarding this function is the pointer_id parameter, which is passed by reference to this function. Although it's an input parameter, ldap_first_attribute() actually uses this parameter to set a pointer that is later...

Editing and Deleting Jokes

The two files that remain, editjoke.php and deletejoke.php, mirror their author and category counterparts, with minor adjustments. editjoke.php must provide the same author select box and category check boxes as newjoke.php, except that this time they must be initialized to reflect those values stored in the database for the particular joke we've selected. deletejoke.php, meanwhile, must delete the selected joke from the joke table, and must also remove any entries in the jokecategory table for...

Your First Application

Now we turn to writing an application so you can see how all these parts come together in a real live application. By the time you have finished reading this introduction, you should have a pretty good idea of how it all comes together. You need a few key elements to get going. We run through them here so you know what you need. This is a Web-based application, so you're clearly going to need a Web server. You will probably be using Apache, whether you are using Windows...

Register.php

The register .ph p page takes care of new user registrations. In this page, you have to provide a form to capture new user details, stop spurious registrations by including a CAPTCHA element, and mail the login details to the new user. As you might recall from the Images and Text section of this book, the Text_CAPTCHA package uses a session variable to store the unique phrase from one page to the next. Therefore, the first thing you need to do is start the session You then include the connect...

Recipe 18.17 Modifying a File in Place Without a Temporary File

You want to change a file without using a temporary file to hold the changes. Read the file into memory, make the changes, and rewrite the file. Open the file with mode r+ (rb+, if necessary, on Windows) and adjust its length with ftruncate( ) after writing out changes open the file for reading and writing fh fopen('pickles.txt,,,r+') or die( php_errormsg) s fread( fh,filesize('pickles.txt')) or die( php_errormsg) modify s seek back to the beginning of the file and write the new s rewind( fh)...

Array_diff()

Array array_diff(array input_array1, array input_array2 , array ) The function array_diff() returns those values located in input_array1 that are not located in any of the other input arrays. This function is essentially the opposite of array_intersect(). An example follows array1 array2 array3 diff array_diff( array1, array2, array3) print_r( intersection)

Installing and Uninstalling Modules

In principle, there are two interesting places in Mambo's administration interface for modules the Module Manager (Modules Site Modules or Modules Administrator Modules) and the Installer. The Installer can notably be found in two places in the administration interface menu at Modules Install Uninstall or at Installer Modules. Which of the two menu commands you select doesn't, however, make any difference functionally or content-wise. j The Home of Mambo - Administration Mambo - Mozilla Firefox...

Array_slice()

Array array_slice(array input_array, int offset , int length ) The array_slice() function returns the section of input_array, starting at the key offset and ending at position offset + length. A positive offset value will cause the slice to begin that many positions from the beginning of the array, while a negative offset value will start the slice that many positions from the end of the array. If the optional length parameter is omitted, the slice will start at offset and end at the last...

Array_splice()

Array array_splice(array input, int offset , int length , array replacement ) The array_splice() function removes all elements of an array, starting at offset and ending at position offset + length, and will return those removed elements in the form of an array. A positive offset value will cause the splice to begin that many positions from the beginning of the array, while a negative offset will start the splice that many positions from the end of the array. If the optional length parameter is...

Substr_replace()

String substr_replace (string str, string replacement, int start , int length ) The substr_replace() function replaces a portion of str with replacement, beginning the substitution at start position of str, and ending at start + length (assuming that the optional input parameter length is included). Alternatively, the substitution will stop on the complete placement of replacement in str. There are several behaviors you should keep in mind regarding the values of start and length If start is...

Effective_cache_size

This setting tells the planner the size of the cache it can expect to be available for a single index scan. Its value is a number equal to one disk page, which is normally 8,192 bytes, and has a default value of 1,000 (8MB RAM). A lower value suggests to the planner that using sequential scans will be favorable, and a higher value suggests that an index scan will be favorable. In most cases, this default is too low, but determining a more appropriate setting can be difficult. The amount you...

Natcasesort()

Void natcasesort(array target_array) The function natcasesort() is functionally identical to natsort(), except that it is case insensitive. Returning to the file-sorting dilemma raised in the natsort() section, suppose that the pictures were named like this Picture1.JPG, picture2.jpg, PICTURE10.jpg, picture20.jpg. The natsort() function would do its best, sorting these items like so PICTURE10.jpg, Picture1.JPG, picture2.jpg, picture20.jpg The natcasesort() function resolves this idiosyncrasy,...

Building a Portable Application Description Template

The Portable Application Description (PAD) is a specification designed by the Association of Shareware Professionals (ASP) you can find it at http www.asp-shareware.org pad . It is a standard format allowing authors of shareware software to provide information such as company and contact information, support information, software information, and licensing in a common format that can be leveraged not only by end users looking for more information about a piece of software but also by online...

Character Sets and Collations

This chapter explains how phpMyAdmin stores and fetches data, and how it deals with the character set and collation features available under MySQL. The program's behavior is highly dependent on the MySQL version used. A character set describes how symbols for a specific language or dialect are encoded. A collation contains rules to compare the characters of a character set. (See the MySQL 4.1.x and Later section in this chapter.) The character set used to store our data may be different from...

Autovacuum

In versions prior to PostgreSQL 8.1, the execution of VACUUM and ANALYZE commands had to be managed manually, or with an extra autovacuum process. Beginning in version 8.1, this automated process has been integrated into the PostgreSQL core code, and can be enabled by setting the autovacuum parameter to TRUE in the postgresql.conf file. When autovacuum is enabled, PostgreSQL will launch an additional server process to periodically connect to each database in the system and review the number of...

Using the xmlrpc_encode_request() Function

Calling the xmlrpc_encode_request() function with the appropriate arguments will create and return a complete XML-RPC request document that includes the methodCall and methodName information string xmlrpc_encode_request(string method, mixed params , array output_options ) The method parameter is simply the name of the method to be called on the remote server. The value passed to this parameter becomes the content of the methodName element in the request. The params parameter contains the PHP...

Validating Form Input

Now that you have a basic understanding of how exceptions work, as well as how to throw and catch custom exceptions, let's apply this learning to a small project that demonstrates these tools in practice. This next example allows the user to place an order for some fine art, by selecting an artist, medium, and price range. The order is then validated, formatted into an e-mail message, and handed to the mail server for delivery. Errors in this process are handled using custom exception handlers,...

Padding String Values 15

In Chapter 14, you read about the PHP trim() function, used to strip leading and trailing white space from string values prior to testing them for validity or inserting them into a database. However, PHP also comes with the str_pad() function, which does just the reverse it pads strings to a specified length using either white space or a user-specified character sequence. This can come in handy if you need to artificially elongate string values for display or layout purposes. Here's a table...

Random_page_cost

Of the settings that control planner costs, this is by far the most often modified by PostgreSQL experts. This setting controls the planner's estimate of the cost of fetching nonsequential pages from disk. The measure is a number representing the multiple of the cost of a sequential page fetch (which by definition is equal to 1) and has a default value of 4. Setting this value lower will increase the tendency to use an index scan, and setting it higher will increase the tendency for a...

Show Columns

Using the SHOW COLUMNS statement, you can gather information about the columns in a table. For some uses of the SHOW COLUMNS statement, the DESCRIBE statement can be substituted. As with other SHOW statements, the SHOW COLUMNS statement supports the use of wildcards. As with the SHOW TABLES statement, the optional FROM < databasename> modifier can be used to look at columns from another database's tables. Welcome to the MySQL monitor. Commands end with or g. Your MySQL connection id is 22...

Preg_split()

Array preg_split (string pattern, string string , int limit , int flags ) The preg_split() function operates exactly like split(), except that pattern can also be defined in terms of a regular expression. If the optional input parameter limit is specified, only limit number of substrings are returned. Consider an example delimitedText fields preg_split( + l, , delimitedText) foreach( fields as field) echo field.< br > Note Later in this chapter, the section titled Alternatives for Regular...

Removing and Replacing Nodes

The last piece of editing a document is removing and replacing nodes in a tree. Some of the methods encountered so far will perform this type of functionality. Take, for instance, the setAttributeNode() method. When a node with the same name exists on the element, the old attribute is removed and replaced with the new attribute node, and the old attribute is returned. The same functionality can happen with other node types using the replaceChild() method. Sometimes, however, you want just to...

Note Not every option has been implemented within the Services_Technorati class. Some are marked as

You pass options as an array where the keys are the names of the options for each value. For example, the cosmos() method is able to accept the type, limit, start, current, claim, and highlight options. To limit the number of results returned to five and add highlighted, linked text, you initialize and pass the options in the following manner options array('limit' > 5, 'highlight' > 1) technorati-> cosmos( url, options) The API is actually quite simple to use. The following example...

Editappt.php (Edit Appointment)

This script performs the only database writing in the project. It also performs the following functions Looks up any appointment for the date time specified Breaks data into fields for display or sets fields to defaults Accepts data submission and checks for errors Encodes data back into the DB field form and stores it in the database The following listing shows the full code for editappt.php 3. List globals for reference 8. Return the variables from GET 10. global date, time, submit_err 11....

Preg_quote()

String preg_quote(string str , string delimiter ) The function preg_quote() inserts a backslash delimiter before every character of special significance to regular expression syntax. These special characters include A * ( ) + < > . The optional parameter delimiter is used to specify what delimiter is used for the regular expression, causing it to also be escaped by a backslash. Consider an example text Tickets for the bout are going for 500. echo preg_quote( text) Tickets for the bout are...

Wrapping Label Text

GtkLabel is useful to display a small amount of text, but small amount is a relative term. Specifically, this means text that does not contain any hard line breaks. This could be anything from one or two words to an entire paragraph. The number of lines a block of text requires depends not only on the length of the string, but also on the properties of the GtkLabel widget. By default, all labels contain one line of text only. The dimensions of the label stretch to fit the text on one line. If...

To create the zip code database:

Which source (of the types and specific ones outlined) you use depends upon your situation. How important is accuracy How much are you willing to spend As a secondary consideration, what resources exist as you're reading this (search the Web and SourceForge) I'll use the version from www.cfdynamics.com zipbase for my example. 2. Create the database (Figure 3.10). CREATE DATABASE zips I'm creating a database called zips, in MySQL, using the mysql command-line client. You could do most of the...

Setting an administrator password for MySQL

The first step immediately after starting a MySQL server is to set a password for the server administrator account known as root. This user is different from the root user on your system setting the password for this user does not affect the password for the root user on your system. (Even so, use care when creating any password, including this one.) The mysqladmin utility is what you use to set the initial password for the root user. To set the password, the command is run twice once for the...

Idle Work

One of the drawbacks to using a timeout is the rigidity with which the callback is called. It will be called every time at the interval defined so long as the callback returns true and the timeout is not removed. It doesn't matter what else needs to be done the callback will be called. This can be somewhat troublesome if the response time of the application is very important. During iterations when the callback is called, the application must first process one event from the event queue then...

Strtr()

String strtr (string str, array replacements) The strtr() function converts all characters in str to their corresponding match found in replacements. This example converts the deprecated bold (< b> ) character to its XHTML equivalent table array(< b> > < strong> , < b> > < strong> ) html < b> Today In PHP-Powered News< b> echo strtr( html, table) < strong> Today In PHP-Powered News< strong>

Understanding the Document

The DOMDocument class is the starting point for all applications using the DOM extension. This class not only serves to create, load, and save XML documents but also contains the factory methods for creating other node type objects. The constructor for this object takes the following form _construct( string version , string encoding ) Both the version and encoding parameters are optional and serve to indicate the version of the XML specification used for the document and to indicate the...

Installing NuSOAP

Installing NuSOAP is really a trivial affair, done in three steps 1. Download the latest stable distribution from http dietrich.ganx4.com nusoap . 2. Extract the package contents to a location convenient for inclusion from a PHP script. Consider placing third-party classes within an aptly named directory located within the PHP_INSTALL_DIR includes directory this is for convenience reasons only, and isn't a requirement. 3. Include the NuSOAP class (nusoap.php) within your script require('nusoap...

Testing Password Guessability with the Crack Lib Library

In an ill-conceived effort to prevent forgetting their passwords, users tend to choose something easy to remember, such as the name of their dog, their mother's maiden name, or even their own name or age. Ironically, this practice often doesn't help users to remember the password and, even worse, offers attackers a rather simple route into an otherwise restricted system, either by researching the user's background and attempting various passwords until the correct one is found, or by using...

Installing Magpie

Like most PHP classes, installing Magpie is as simple as placing the relevant files within a directory that can later be referenced from a PHP script. The instructions for doing so follow 1. Download Magpie from http magpierss. sourceforge .net . 2. Extract the package contents to a location convenient for inclusion from a PHP script. For instance, consider placing third-party classes within an aptly named directory located within the PHP_INSTALL_DIR includes directory. Note that you can forego...

To process a Quick Form:

Open quickform.php (Script 12.4) in your text editor or IDE, if it is not already. 2. Remove the current invocation of the display() method (Script 12.5). I will change when this method is called. Script 12.5 The final step in the form process is to do something with the submitted data. A conditional added here lists all the submitted data if the form passes validation, and shows the form otherwise. < DOCTYPE html PUBLIC - W3C DTD XHTML 1.0 Transitional EN < html xml lang en lang en> <...

Using Application Express

APEX, formerly known as HTML DB, is a rapid Web application development tool requiring little or no programming experience. The applications you develop with APEX connect to any Oracle database, including Oracle Database XE, and therefore automatically inherit the scalability and security features inherent in an Oracle database. APEX is completely menu driven. You use application wizards to create a new application or even convert an old application to a more robust platform. For example, you...

Setting Transparency

Images can not only define visible pixels, but they also can define pixels that cannot be seen. These pixels are transparent. Transparent pixels allow the user to see through parts of an image. Transparent pixels are useful in cases where an image is a unique shape and you do not want to have a solid-colored background. For example, let's say that the products can be rated from zero to five stars based on how well they sell. In order to make the application look clean and professional, the star...

Autoincrement and autodecrement

It's very common when writing your code to either increment or decrement a variable by one. It's so common that PHP has a special shortcut for doing it. The autoincrement operator is ++ and is used like this This is completely equivalent to, and even more professional-looking, than counter+ 1 Example 3-23 adds one to counter. Example 3-23. Using autoincrement to add to a variable < php The same concept applies to the automatic decrement operator, --. Example 3-24 subtracts one from counter....

Linking to a Detailed View

Often a user will want to do more with the results than just view them. For example, the user might want to learn more about a particular product found in the result, or he might want to add a product to his shopping cart. An interface that offers such capabilities is presented in Figure 31-2. Figure 31-2. Offering actionable options in the table output As it currently stands, the getResultsAsTable() method doesn't offer the ability to accompany each row with actionable options. This section...

Tabular Output

Viewing retrieved database data in a coherent, user-friendly fashion is key to the success of a Web application. HTML tables have been used for years to satisfy this need for uniformity, for better or for worse. Because this functionality is so commonplace, it makes sense to encapsulate this functionality in a function, and call that function whenever database results should be formatted in this fashion. This section demonstrates one way to accomplish this. For reasons of convenience, we'll...

Creating Paged Output

If you've perused any e-commerce sites or search engines, you're familiar with the concept of separating output into several pages. This feature is convenient not only to enhance readability, but also to further optimize page loading. You might be surprised to learn that adding this feature to your Web site is a trivial affair. This section demonstrates how this is accomplished. This feature depends in part on two SQL clauses LIMIT and OF FSET. The LIMIT clause is used to specify the number of...

Printf()

Boolean printf (string format , mixed args ) The printf() function is functionally identical to print (), outputting the arguments specified in args, except that the output is formatted according to format. The format parameter allows you to wield considerable control over the output data, be it in terms of alignment, precision, type, or position. The argument consists of up to five components, which should appear in format in the following order Padding specifier This optional component...

Passing Arguments by Reference

On occasion, you may want any changes made to an argument within a function to be reflected outside of the function's scope. Passing the argument by reference accomplishes this need. Passing an argument by reference is done by appending an ampersand to the front of the argument. An example follows function calculate_cost(& cost, tax) Perform some random change to the tax variable. echo Tax is . tax*100.< br > echo Cost is . cost.< br > Note that the value of tax remains the same,...

8.2.3 Graphing the Balance of a Single Account over Time, with a Moving Average

A bar graph of account values every seven days during a specified time period is useful, but it would be better if there were a line showing the changes in a 60-day moving average each week. With such a line visible, the user of Currawong Accounting could see whether the balance of the account was, overall, tending to increase or decrease. In some modifications are made to the program discussed in the preceding section to enable the addition of such a trend line. This program takes its input...

Xpath()

Array simplexml_element-> xpath (string path) XPath is a W3C standard that offers an intuitive, path-based syntax for identifying XML nodes. For example, referring to the books. xml document, you could retrieve all author nodes using the expression library book author. XPath also offers a set of functions for selectively retrieving nodes based on value. Suppose you want to retrieve all authors found in the books. xml document xml authors foreach( authors AS author) echo author< br > Jane...

Producing the SQL

The last step of Logical Design is creation of the SQL for the database. As this point, you must make some important decisions involving column types and constraints for the candidate tables. There are a number of column types supported by MySQL. Refer to Appendix A for a complete listing of column types supported by MySQL. Recalling Figure 7-10's candidate tables, I recommend using integer type for the ID columns in all tables. Further, I would recommend column types of varchar for the name...

Creating a Simple RSS 2.0 Parser Using SimpleXML

SimpleXML provides a simple way to parse feeds. As long as no default namespaces have been used in the feeds, you have little to deal with other than understanding the structure. As you are already aware from Chapter 7, you access elements as properties by name, and you access attributes like an array with string indexes. * Define some RSS 2.0 and other compatible feeds * rssfeed array() * The PHP RSS feeds are RSS version 0.93 * rssfeed 'PHPGEN' * The YAHOO RSS feeds are RSS version 2.0 *...

Strrpos()

Int strrpos (string str, char substr , offset ) The strrpos() function finds the last occurrence of substr in str, returning its numerical position. The optional parameter offset determines the position from which strrpos() will begin searching. Suppose you wanted to pare down lengthy news summaries, truncating the summary and replacing the truncated component with an ellipsis. However, rather than simply cut off the summary explicitly at the desired length, you want it to operate in a...

Installing PHP-GTK 2 on Linux

The first step in getting PHP-GTK running on a Linux system is installing GTK. Most systems these days come with GTK+ 2.x already installed. Chances are your system already meets the minimum requirements for PHP-GTK, which is GTK+ 2.6.0. Before downloading and configuring anything, double-check that your system doesn't already have the necessary files. To verify that you have the right packages and versions, use the pkg-config utility, which comes standard on most Linux distributions. Try...

Naming Conventions

Simply put, if you don't name your files correctly, Cake won't be able to piece the different parts of the application together and will supply you with error messages. Each element of the site must follow certain naming conventions so that when Cake looks for a needed resource, it can find it and run it. You probably noticed in Chapter 3 that you gave certain names to the model and controller files to make the to-do list application work. I explained that these files have to match up with the...

Working with Strings

Many databases (including MySQL) will automatically truncate string values if they exceed the length specified for the corresponding field. This is disturbing, because it means that user input can easily (and silently) get corrupted without a notification being raised. So, it's usually a good idea to perform application-level input validation of string values, to alert users if their input goes above the prescribed limit and to allow them to modify it. A good place to start for this kind of...

Safe_mode_include_dir (string)

Scope PHP_INI_SYSTEM Default value NULL You can use safe_mode_include_dir to designate various paths in which safe mode will be ignored if it's enabled. For instance, you might use this function to specify a directory containing various templates that might be incorporated into several user Web sites. You can specify multiple directories by separating each with a colon on Unix-based systems, and a semicolon on Windows. Note that specifying a particular path without a tailing slash will cause...

Sending a Plain-Text E-Mail

Sending the simplest of e-mails is trivial using the mail() function, done using just the three required parameters. Here's an example mail(test example.com, This is a subject, This is the mail body) Try swapping out the placeholder recipient address with your own and executing this on your server. The mail should arrive in your inbox within a few moments. If you've executed this script on a Windows server, the From field should denote whatever e-mail address you assigned to the sendmail_from...

Safe_mode (boolean)

Scope PHP_INI_SYSTEM, Default value 0 Enabling the safe_mode directive places restrictions on several potentially dangerous language features when using PHP in a shared environment. You can enable safe_mode by setting it to the Boolean value of on, or disable it by setting it to off. Its restriction scheme is based on comparing the UID (user ID) of the executing script and the UID of the file that the script is attempting to access. If the UIDs are the same, the script can execute otherwise,...

Configuration

If you've made it this far, congratulations You have an operating Apache and PHP server at your disposal. However, you'll probably need to make at least a few other run-time changes before the software is working to your satisfaction. The vast majority of these changes are handled through Apache's httpd.conf file and PHP's php.ini file. Each file contains a myriad of configuration directives that collectively control the behavior of each product. For the remainder of this chapter, we'll focus...

Beware of pg_query()

The pg_query () function behaves in a fashion that perhaps isn't as intuitive as you might think. Not completely understanding its behavior could play havoc with your transactional logic. This confusion can arise from the manner in which pg_query() determines success and failure. When pg_query() is called, any successfully executed query will return a resource identifier. This may seem straightforward, but you must remember that just because a query executed successfully does not mean anything...

AJAX/Java Script

The wiki contains two AJAX packages one using XAJAX, and the other the prototype.js scriptaculous.js libraries. http www.codeigniter.com wiki AJAX for CodeIgniter Uses the prototype.js and scriptaculous.js libraries Download includes .js files as well as .php and a full User Guide. (This is not easy to understand if you don't already have a good grasp of AJAX and the DOM, and it could usefully have had some longer examples.) Simple to install place the .php file in your application libraries...

Variable scope

To work with functions you need to understand how PHP handles variable scope. Scope is an important topic in any programming language, and PHP is no different. In PHP, variables assigned outside of functions are known as global variables. These can be variables that you create, they can come from HTML form elements through either GET or POST, or they can be any of the variables inherited from the Apache environment. All globals are accessible from an array known as GLOBALS. You can add to and...

Polymorphism

Polymorphism, a term originating from the Greek language that means having multiple forms, is perhaps the coolest feature of OOP. Simply defined, polymorphism defines OOP's ability to redefine, or morph, a class's characteristic or behavior depending upon the context in which it is used. This is perhaps best explained with an example. Returning to the employee example, suppose that a behavior titled clock_in was included within the employee definition. For employees of class clerk, this...

Ucfirst()

The ucfirst () function capitalizes the first letter of the string str, if it is alphabetical. Nonalpha-betical characters will not be affected. Additionally, any capitalized characters found in the string will be left untouched. Consider this example sentence the newest version of PHP was released today echo ucfirst( sentence) The newest version of PHP was released today Note that while the first letter is indeed capitalized, the capitalized word PHP was left untouched.

Method_Description_

ReadInnerXml() Returns a string containing the contents of the current node, which includes child nodes and markup. readOuterXml() Returns a string containing the current node and all of its contents, which includes child nodes and markup. readString() Returns a string containing the contents an element or text node. When posi tioned on an element, the content of all text and CDATA nodes within the subtree of the element are concatenated together in the resulting string. The example in Listing...

SimpleXML Extension

No time has been wasted with the SimpleXML extension. As of PHP 5.1.2, two new methods have been introduced, getNamespaces() and getDocNamespaces(), and the resulting structure from calling var_dump() with a SimpleXMLElement has changed for the better. Working with namespaced documents is probably the area that causes the most problems for developers working with SimpleXML. To access an element or attribute within a namespace, and not the default namespace, you must specify the namespace URI....

The XSLTProcessor Methods

Table 10-3 lists the methods implemented by the XSLTProcessor class. Gets the value of a parameter Determines whether PHP has EXSLT support Imports style sheet Enables the ability to use PHP functions as XSLT functions The descriptions for these methods are generic. You'll see explanations and examples of these methods in the next section.

1.4 Questions and Exercises

What metrics would you use, in other words, what would you measure, to determine when a multi-tier software system that was hosted on a single machine should be spread out across several computers 2. How might you design the data network that would host a multi-tier application Consider network latency, security, and ease-of-access requirements. 3. If demands on its database were such that an organization wanted to spread the database management services across multiple machines, what are...

Web Services

Before Ajax became all the rage, web services was the talk of the town. How could it not be, really Web services is a very exciting concept, both for those wishing to allow use of their custom code and information sets, and those eager to make use of such functionality. Basically, web services provide an interface for developers to perform certain operations on a computer external to the script calling the function. Site owners who wish to provide external access to information in their...

Code Changes

As usual, a complete version of the code discussed in this application is available from the book's website. The directory structure for the files accompanying this chapter is the same as those for Chapter 15, so you shouldn't have trouble finding your way around. Also, as usual, I won't reproduce all the code in this chapter, only relevant sections. We'll start by looking at the constructor. NOTE The application we developed in Chapter 15 uses version 2 of SQLite. Take this opportunity to...

Preg_match()

Int preg_match (string pattern, string string , array matches , int flags , int offset ) The preg_match() function searches string for pattern, returning TRUE if it exists and FALSE otherwise. The optional input parameter pattern_array can contain various sections of the subpatterns contained in the search pattern, if applicable. Here's an example that uses preg_match() to perform a case-sensitive search line Vim is the greatest word processor ever created if (preg_match( bVim b i, line,...

Strcmp()

Int strcmp (string strl, string str2) The strcmp() function performs a binary-safe, case-sensitive comparison of the strings str1 and str2, returning one of three possible values 0 if strl and str2 are equal -1 if strl is less than str2 1 if str2 is less than strl Web sites often require a registering user to enter and confirm his chosen password, lessening the possibility of an incorrectly entered password as a result of a typing error. Because passwords are often case sensitive, strcmp() is a...

Importing and Exporting Data with phpPgAdmin

If you're looking for a convenient and powerful administration utility that is capable of being accessed from anywhere you have a Web browser, phpPgAdmin (http www.phppgadmin.net ) is the most capable solution around. First introduced in Chapter 27, phpPgAdmin is capable of managing your database with ease, in addition to both importing and exporting data in a variety of formats. Note At the time of writing, using this phpPgAdmin feature with Windows is not supported. To export data, navigate...

A Soap Client

To make use of a web service, we need to create a SOAP client. The first step in creating a client for the Google API is reading the WSDL description of the service found at SOAP allows us to create a client object using the information in this file. We will then invoke the doGoogleSearch method of this object. Let's step through the code in our usual fashion beginning with the file dosearch.php. This is the file that actually does the search before handing the results over to an AJAX call. The...

Server Operations

The Status, Variables, and Processes links are available to get information about the MySQL server or to act upon specific processes. These statistics reflect the MySQL server's total activity, including (but not limited to) the activity generated by queries sent from phpMyAdmin. Clicking the Status link produces runtime information about the server. The page has several sections. First we get information about the elapsed running time and the startup time, and then we get the total and average...

Database Exports

In Database view, click the Export link. The default export panel looks like this The default values selected here depend on config.inc.php, more specifically on the cfg 'Export' array of parameters. For example, the cfg ,Export, ,format' parameter is set to 'sql' so that the SQL export mode is chosen by default. The default values selected here depend on config.inc.php, more specifically on the cfg 'Export' array of parameters. For example, the cfg ,Export, ,format' parameter is set to 'sql'...

XML_DTD Package

XML_DTD offers the capabilities to parse DTDs as well as validate documents against these DTDs without needing a validating parser such as DOM. In fact, the only dependency this package has is the XML_Tree package and its dependencies. The package consists of three classes. XML_DTD_Parser performs the actually parsing of a DTD, which results in an object of the XML_DTD_Tree class. You can use this to extract information from the parsed DTD. The last class, XML_DTD_XmlValidator, validates an XML...

Mcrypt_decrypt()

String mcrypt_decrypt(string cipher, string key, string data, string mode , string iv ) The mcrypt_decrypt() function decrypts a previously encrypted cipher, provided that the cipher, key, and mode are the same as those used to encrypt the data. Go ahead and insert the following line into the previous example, directly after the last statement echo mcrypt_decrypt(MCRYPT_DES, key, enc, MCRYPT_MODE_CBC, iv) This is the message I want to encrypt. The methods in this section are only those that are...

Expanding and Contracting Content

One spectacular use for Ajax-type functionality is in hiding content away and exposing it based on link clicks (or hovers, or button presses). This sort of functionality allows you to create access to a large amount of content without cluttering the screen. By hiding content within expandable and retractable menu links, you can add a lot of information in a small amount of space. Consider the following example, which uses Ajax to expand and contract a calendar based upon link clicks. By using...

Creating a Subnet Converter

You've probably at one time scratched your head trying to figure out some obscure network configuration issue. Most commonly, the culprit for such woes seems to center on a faulty or an unplugged network cable. Perhaps the second most common problem is a mistake made when calculating the necessary basic network ingredients IP addressing, subnet mask, broadcast address, network address, and the like. To remedy this, a few PHP functions and bitwise operations can be coaxed into doing the...