25. Custom Web Publishing with PHP and XML

About Custom Web Publishing

Custom Web Publishing (CWP) is one of two technologies you can use to dynamically publish your FileMaker data on the World Wide Web. Custom Web Publishing comes in two variations: One lets you work with XML, and the other lets you work with PHP. Both are described in this chapter.

Image In addition to Custom Web Publishing, Instant Web Publishing, which you can read about in Chapter 24, “Instant Web Publishing,” also lets you publish your database to the Web.

This chapter assumes a basic familiarity with PHP and XML—or just one of them, if that’s all you want to use. Additional documentation is installed with FileMaker Server in its Documentation folder: You will find separate documents for XML and PHP publishing. On OS X, FileMaker Server is installed in /Library/FileMaker Server/Documentation rather than in /Applications. On Windows, it is Program FilesFileMakerFilemaker ServerDocumentation.


Image Note

In FileMaker Pro, it’s possible to use Instant Web Publishing (IWP) to publish data from a client copy of FileMaker Pro. IWP can also be used in FileMaker Server Advanced, though, and can support many up to 100 users in that way.


Image For more detail about the two different flavors in the FileMaker Server product line, FileMaker Server and FileMaker Server Advanced, see Chapter 27, “FileMaker Server and Server Advanced.”

Without web publishing, the only access to your databases will be directly through the FileMaker Database server using FileMaker Pro and FileMaker Go clients. If you have FileMaker Server Advanced, you will be able to enable ODBC/JDBC, which will allow access to your databases from ODBC/JDBC clients other than FileMaker.


Image Tip

FileMaker Server provides the web publishing capabilities for CWP with PHP or XML. For Open Database Connectivity/Java Database Connectivity (ODBC/JDBC) or Instant Web Publishing beyond a single computer, you need FileMaker Server Advanced.


Most installations do enable web publishing if only because they allow so many deployment options, and because FileMaker Server supports web publishing except for Instant Web Publishing and ODBC/JDBC, which require FileMaker Server Advanced. When you install FileMaker Server or FileMaker Server Advanced, you deploy it over one, two, or three computers.


Image Tip

FileMaker Server need not have web publishing enabled. However, if it is not enabled, you will not be able to use Instant Web Publishing or Custom Web Publishing with PHP or XML.


Understanding the Three Parts of FileMaker Web Publishing

Regardless of the number of computers you use, you must know about these three parts of FileMaker web publishing:

Web server—Apache (OS X) or IIS (Windows). During installation, the FileMaker Web Server Module is installed into the web server. In addition, the FileMaker PHP application programming interface may be installed on the web server.

Web Publishing Engine (WPE)—The code that handles web publishing. It includes the Web Publishing Core, which routes requests from the Web Server Module inside the web server to the FileMaker Database Server. It also includes the Custom Web Publishing Engine (CWPE), which routes return information to the web server.

FileMaker Database Server—The basic server to which you connect from FileMaker Pro and FileMaker Go clients.

What is critically important is that the users use web browsers to access the web server just as they normally would to access any web page. The Web Server Module installed by FileMaker routes the requests to the WPE and the FileMaker Database Server.

Custom Web Publishing Versus Instant Web Publishing

If you’ve read about Instant Web Publishing already in Chapter 24, you’ll be aware that the IWP capabilities of FileMaker are quite extensive—so extensive, in fact, that you might wonder whether IWP would suffice for all your web publishing needs. But CWP has a number of important advantages over IWP. Here are some of the most significant ones:

• With CWP, integrating FileMaker data with other websites or providing FileMaker data to others in the form of a web service is straightforward. CWP makes a strong distinction between the raw data (which is returned as XML) and the final presentational form (which can result from writing PHP code). By contrast, in IWP, data and presentation combine in a way that makes it all but impossible to use the data itself in other contexts.

• CWP is best for sites that need to conform to the conventions of the World Wide Web. IWP presents data in a FileMaker-driven way: It’s easy, using IWP, to reproduce a complex FileMaker layout on the Web. But it would be quite difficult to, for example, display a set of search results in a two-column list or break up a large set of search results into multiple results pages—both of which are common presentation styles on the Web.

• IWP has a number of built-in limitations. For example, it cannot reproduce FileMaker’s Preview mode. In addition, the IWP list and table views are limited to displaying 25 and 50 records at a time, respectively. CWP can overcome these limits.

In general, IWP is best for making some portion of the functionality of an existing FileMaker database accessible to remote users. IWP’s chief strength is in bringing the FileMaker experience into a web browser. The most likely targets for this technology are remote users of a FileMaker system who might not be able to be in the same building or same site as the server, but require ready access. This is likely to cater to a relatively small group of users—hundreds, say, rather than the thousands and tens of thousands that a public website can reach.

CWP, on the other hand, is best when you want to present FileMaker data in a non-FileMaker style, either as familiar-looking web pages or in some other form. It enables you to make FileMaker data available over the Web as raw XML, to integrate FileMaker data into an existing website, or to build a new website around FileMaker data while preserving all the conventions of web presentation. In addition, the rich set of PHP functions provided by FileMaker let you enhance the user experience tremendously.

Preparing for Custom Web Publishing

CWP requires you to have FileMaker Server or FileMaker Server Advanced installed alongside a web server. Beyond that, you must prepare each database that will use CWP, and you must enable the appropriate CWP technologies on FileMaker Server.

Image For more information on FileMaker Server and FileMaker Server Advanced, see Chapter 27, “FileMaker Server and Server Advanced.”

Getting Your Databases Ready for CWP

To get your FileMaker databases ready for CWP, you need to do a few specific things with access privileges in each file you want to share via CWP. If you’re familiar with previous versions of FileMaker Pro, you’ll recall that the various publishing options for a database (web sharing, local ODBC, remote ODBC) were all accessed via a file’s sharing options. Enabling or disabling a sharing method was simply a matter of checking or unchecking a sharing option.

Access to a FileMaker database using XML is handled via the security and privilege system. You can allow or deny XML access to a file based on whether a user has the appropriate privilege, as well as control that user’s rights and privileges down to the record or field level.

To enable CWP in a file, you must enable the correct extended privileges for each type of CWP access you want to allow. To allow access to data from the file as raw XML, enable the extended privilege with the keyword fmxml, as shown in Figure 25.1.

Image

Figure 25.1. You must enable certain extended privileges to enable Custom Web Publishing with XML.

To recap, each database that you want to share via CWP must have the appropriate extended privileges created and added to one or more privilege sets.

Image If you expect to see a database served via CWP and it doesn’t appear, check to make sure that the appropriate extended privileges are enabled. SeeGetting the Right Privileges” in the “Troubleshooting” section at the end of this chapter.


Image Tip

In Figure 25.1, one important point to note is that FileMaker network access is enabled. If it is, you can use the Open Remote command in FileMaker Pro to access the database being shared by FileMaker Server. This is an important safety valve for you because it enables you to log on and make changes to accounts and privileges, for example. In general, providing yourself with at least one account that has network access to each shared database is a good idea.


Getting FileMaker Server Ready for Custom Web Publishing

You also must configure FileMaker Server for the CWP technologies you will be using. The general settings in Admin Console are shown in Figure 25.2. The section for each CWP technology shows you what the settings are.

Image

Figure 25.2. Set general CWP settings.

Use the General Settings tab of Web Publishing to adjust the settings. At least for development, you usually do want the logs enabled.

Choosing a Custom Web Publishing Technology

Both XML and PHP are powerful tools for Custom Web Publishing (CWP). Choosing between them depends exactly on what you are trying to do and what your resources are. Perhaps most important, if the developer of your CWP site is more comfortable with PHP than XML, or vice versa, your choice is basically made for you. Let the technology work around the people, not the other way around. Here are some general considerations you might want to contemplate:

• PHP is an object-oriented procedural scripting language. The XML combination is more declarative. Some web developers prefer one style to the other.

• It might be easier to integrate PHP into a site that uses other web technologies.

There are also some considerations you don’t have to worry about in making your choice. These apply to both forms of CWP:

• FileMaker handles all security using accounts, privileges, and extended privileges.

• Both XML and PHP are controlled by FileMaker Server. They are also available on FileMaker Server Advanced, but the basic FileMaker Server product can serve up both forms of web publishing.

Using Custom Web Publishing with PHP

CWP requires that you have FileMaker Server or FileMaker Server Advanced installed alongside a web server. In addition to that, you have to prepare each database that will use CWP, and you must enable the appropriate CWP technologies on FileMaker Server.

Image For more information on FileMaker Server and Server Advanced, see Chapter 27, “FileMaker Server and Server Advanced.”

Image For more information on Custom Web Publishing with PHP, see the FileMaker documentation installed in the Documentation folder of FileMaker Server.

Getting Your Databases Ready for Custom Web Publishing with PHP

Access to a FileMaker database via PHP is handled via the security and privilege system. You can allow or deny PHP access to a file based on whether a user has the appropriate privilege, and you can control that user’s rights and privileges down to the record or field level.

Setting the Extended Privilege for PHP

To allow access via PHP, enable the extended privilege with the keyword fmphp. Figure 25.1 illustrates the use of these extended privileges.


Image Tip

If you expect to see a database served via CWP/PHP and it doesn’t appear, check to make sure the appropriate extended privileges are enabled.


Setting Other Security Measures for the Database

In addition to setting the extended privilege for PHP, you can also take a variety of other steps if you choose. Still in the area of security and access, you might want to review the accounts and privileges you have set for the database. Even if you are behind a corporate firewall, you often want to limit web access to your database to the absolute minimum. If you are publishing public data in a totally public environment, it is still worth occasionally reviewing your database to make certain that, in its ongoing maintenance and modification, no confidential data has appeared there.


Image Note

This security issue is particularly relevant to organizations such as schools where the internally public data (class lists, student addresses, and so forth) is generally never shown in public.


Getting FileMaker Server Ready for Custom Web Publishing with PHP

You also must use Admin Console to enable PHP publishing, as shown in Figure 25.3. The other options in this window are described later in this chapter.

Image

Figure 25.3. Enable PHP publishing in Admin Console.

Placing Files on the Web Server

The two types of files you need to worry about placing on the web server are the PHP files themselves and the files that are referred to by container fields.

Placing the PHP Files

When you are using Custom Web Publishing with PHP, your PHP files live in the normal web publishing folder on the web server. If you are using multiple machines, the Admin Console setup establishes the link between the web server and the machine running the Web Publishing Engine.

Dealing with Container Fields

Beginning with FileMaker 12, it is possible to specify the location of container field data. By default, container files are placed in a folder adjacent to the databases. This means that on FileMaker Pro server, your databases folder (which may contain a subfolder) contains databases and a folder for the container content, as you see in Figure 25.4. On Windows, the databases are in Program FilesFileMakerFileMaker ServerDataDatabase<optional subfolder>. On OS X, the location is /Library/FileMaker Server/Data/Databases/<optional subfolder>/.

Image

Figure 25.4. Location container folders.

Within the optional subfolder, you will find a folder for each database, as shown in Figure 25.5.

Image

Figure 25.5. Subfolders for each database hold container files.

Image For more on container fields, see Chapter 3, “Defining and Working with Fields and Tables.”

Writing the PHP code for the FileMaker PHP API

The heart of the FileMaker PHP implementation is the FileMaker class. Typically, you include it in each of your FileMaker PHP files, as shown here:

require_once ('FileMaker.php'),

The file is located in Applications/FileMaker API for PHP/ along with examples and further documentation. It is worth reviewing that file as you plan your code: All of the methods are located in that file and they are documented thoroughly.

The structure of FileMaker PHP files is usually the same. The FileMaker API for PHP/examples/API/examples/viewRecord.php file is a good example. The file consists of six sections, which are detailed next. Note that some spacing has been modified for the book’s layout.

Typical PHP Headers

The beginning of the file consists of the standard opening code for a PHP file:

<html>
<?php

Comments and Documentation

Next, comments and documentation of the file are provided (you do provide comments, don’t you?):

/*
 * viewRecord.php
 *
 * Copyright  © 2005-2006, FileMaker, Inc. All rights reserved.
 * NOTE: Use of this source code is subject to the terms of the FileMaker
 * Software License which accompanies the code. Your use of this source code
 * signifies your agreement to such license terms and conditions. Except as
 * expressly granted in the Software License, no other copyright, patent, or
 * other intellectual property license or right is granted, either expressly or
 * by implication, by FileMaker.
 *
 * Example PHP script to illustrate how to view a particular record in a
 * database using PHP API.
 *
 * Requirements:
 *   1. Working FileMaker Server Advanced installation
 *   2. 'FMPHP_Sample' database hosted in FileMaker Server
 *
 */

Get the FileMaker Object and Store It

Next, you include FileMaker.php and access the FileMaker object. Then you set up some other variables that you might need. Most commonly, you want to get a database.

Here is the standard code to access a database and store it in a variable:

// Include FileMaker API
require_once ('FileMaker.php'),

// Create a new connection to FMPHP_Sample database.
// Location of FileMaker Server Advanced is assumed to be on the same machine,
//  thus we assume hostspec is api default of 'http://localhost' as specified
//  in filemaker-api.php.
// If FMSA web server is on another machine, specify 'hostspec' as follows:
//   $fm = new FileMaker('FMPHP_Sample', 'http://10.0.0.1'),
$fm = new FileMaker('FMPHP_Sample'),

The last line stores the FileMaker object in a local variable ($fm is the name commonly used). Note that there are only two executable lines of code in this snippet:

require_once ('FileMaker.php'), is usually the first executable line of code. It is unchanged in your various FileMaker PHP files.

$fm = new FileMaker accesses a database and stores it in a variable. The argument is the name of the database.

Get a Record from the FileMaker Object ($fm) as Needed

Store data such as a record in a local variable and close the PHP section:

// Since we're passed in recid via param (i.e. viewRecord.php?recid=n), use
// FileMaker::getRecordById() to directly get record object with recid accessed
// via $_GET[] array
$record = $fm->getRecordById('Form View', $_GET['recid']);

if (FileMaker::isError($record)) {
    echo "<body>Error: " . $record->getMessage(). "</body>";
    exit;
}
?>

Now you can use $record in your code.


Image Tip

In many cases, two people write this code: One knows FileMaker and the other knows HTML. You can use this formatting so that they stay out of each other’s way. Perhaps the HTML author writes the code for the table and inserts comments for the FileMaker access. Alternatively, the FileMaker author can write code for the PHP accesses of the necessary fields, and the HTML author works around that code to put the data into a table or other page elements.


Get Data from a Record

Finally, you write the HTML code for the page head and body. The code has been reformatted to make it more obvious that you are using PHP snippets to move data from $record into the page layout structures (a table and the page title in this case).

<head>
<title>
  <?php echo $record->getField('Title'), ?>
</title>
<!-- declare charset as UTF-8 -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="style.css">
</head>
<body>
<table>
<tr><th id="table-title" colspan="3">America 24/7 Collection</th></tr>
<tr><th>Title</th><td>
  <?php echo $record->getField('Title'), ?>
  </td></tr>
<tr><th>Author</th><td>
  <?php echo $record->getField('Author'), ?>
  </td></tr>
<tr><th>Publisher</th><td><?php echo $record->getField('Publisher'), ?>
  </td></tr>
<tr><th>Cover Photo Credit</th><td><?php echo
  $record->getField('Cover Photo Credit'), ?>
  </td></tr>
<tr><th>Number of Pages</th><td>
  <?php echo $record->getField('Number of Pages'), ?>
  </td></tr>
<tr><th>Status</th><td>
  <?php echo $record->getField('Status'), ?>
  </td></tr>
<tr><th>Quantity in Stock</th><td>
  <?php echo $record->getField('Quantity in Stock'), ?>
  </td></tr>
<tr><th>Description</th><td>
  <?php echo $record->getField('Description'), ?>
  </td></tr>
<tr><th>Cover Image</th><td>
  <?php if ($record->getField('Cover Image')) {?>
    <IMG src="containerBridge.php?path=
    <?php echo urlencode($record->getField('Cover Image')); ?>
    ">
    <?php } ?>
  </td></tr>
<tr><td colspan="2" style="text-align: center">
  <a href="editRecord.php?recid=<?php echo
    $record->getRecordId(); ?>">Edit this record
  </a></td></tr>
<tr><td colspan="2" style="text-align: center">
  <a href="deleteRecord.php?recid=
    <?php echo $record->getRecordId(); ?>">Delete this record</a>
  </td></tr>
<tr><td colspan="2" style="text-align: center">
  <a href="displayRecords.php">Back to Record List</a>
  </td></tr>
</table>
</body>

Close the HTML Section

As always, you have to terminate the HTML element that you opened on the first line of the file:

</html>

Using Custom Web Publishing with XML

Preparing for XML Publishing

To publish FileMaker data as XML via the Web Publishing Engine, you must configure your databases for XML publishing as described in the previous section. You also need to enable XML publishing in the Configuration tab of Admin Console, as shown in Figure 25.6.

Image

Figure 25.6. Enable XML publishing in Admin Console.

Introduction to XML Publishing

After you have enabled XML publishing in the database and in Admin Console, you can draw XML data from a served database by opening a web browser and entering a URL like the following:

http://192.168.100.101/fmi/xml/fmresultset.xml?-db=Animal&-lay=web&-findall

This URL, 192.168.100.101, is the address of the web server that we’ve configured to work with the Web Publishing Engine. The path to fmresultset.xml indicates that we want the results returned in the fmresultset grammar. The URL also instructs the WPE to access a database called Animal, via a layout called Web, and then to find all records and return them in the select fmresultset grammar.


Image Note

You do not need to include the filename suffix (.fp7 or .fp12) when referencing the database name in the URL.


If you had a database called Animal open under FileMaker Server, and if it had privilege sets with the extended privilege for XML enabled, and it had a layout called Web, the Web Publishing Engine would return an XML document to your browser. If you’re using a browser capable of displaying XML (which includes Firefox, Safari, and Internet Explorer), you would see something like the code in Listing 25.1.

Listing 25.1. XML Formatted with the fmresultset Grammar

<?xml version="1.0" standalone="no"?>
<!DOCTYPE fmresultset PUBLIC "-//FMI//DTD fmresultset//EN" "/fmi/xml/fmresultset.dtd">
<fmresultset xmlns="http://www.filemaker.com/xml/fmresultset" version="1.0">
    <error code="0">
    </error>
    <product build="12/10/2003" name="FileMaker Web Publishing Engine" version="7.0v1" />
         <datasource database="animal" date-format="M/d/yy" layout="web" table="Animal" time-format="h:mm:ss a" total-count="17" />
         <metadata>
        <field-definition auto-enter="no" global="no" max-repeat="1" name="date_birth" not-empty="no" result="date" type="normal" />
        <field-definition auto-enter="yes" global="no" max-repeat="1" name="id_animal" not-empty="yes" result="text" type="normal" />
        <field-definition auto-enter="no" global="no" max-repeat="1" name="id_father" not-empty="no" result="text" type="normal" />
        <field-definition auto-enter="no" global="no" max-repeat="1" name="id_mother" not-empty="no" result="text" type="normal" />
        <field-definition auto-enter="no" global="no" max-repeat="1" name="name" not-empty="no" result="text" type="normal" />
        <field-definition auto-enter="no" global="no" max-repeat="1" name="weight_birth" not-empty="no" result="number" type="normal" />
        <field-definition auto-enter="no" global="no" max-repeat="1" name="weight_current" not-empty="no" result="number" type="normal" />
        <field-definition auto-enter="no" global="no" max-repeat="1" name="HerdID" not-empty="no" result="text" type="normal" />
        <field-definition auto-enter="no" global="no" max-repeat="1" name="gender" not-empty="no" result="text" type="normal" />
    </metadata>
    <resultset count="17" fetch-size="17">
        <record mod-id="6" record-id="1">
            <field name="date_birth">
                <data>4/23/1994</data>
            </field>
            <field name="id_animal">
                <data>A1</data>
            </field>
            <field name="id_father">
                <data></data>
            </field>
            <field name="id_mother">
                <data></data>
            </field>
            <field name="name">
                <data>Great Geronimo</data>
            </field>
            <field name="weight_birth">
                <data>107</data>
            </field>
            <field name="weight_current">
                <data>812</data>
            </field>
            <field name="HerdID">
                <data>H1</data>
            </field>
            <field name="gender">
                <data>Male</data>
            </field>
        </record>
        [ ... multiple additional records ...]
    </resultset>
</fmresultset>

In general, when you want to access XML data from an appropriately configured FileMaker file, you do so by entering a URL in the following format:

<protocol>//<server-ip>[:<port>]/fmi/xml/<grammar>.xml?[<query-string>]

protocol indicates a web protocol, either HTTP or HTTPS.

server-ip is the IP address of the web server that serves as the point of entry to the Web Publishing Engine. Note that if the Web Publishing Engine is installed on a different machine from the web server, you must specify the IP address of the web server machine here, providing the address of the Web Publishing Engine does not work.

port is an optional part of the URL. In general, your web server will be running on the default HTTP port of 80 or the default HTTPS port of 443. If for any reason you’ve configured your web server to run on a different port than the protocol default, you need to specify that port number here. This port has nothing to do with any of the WPE-specific ports (in the 16000 range) or the FileMaker Server port (5003) that you might have encountered in the Web Publishing Engine documentation; it refers strictly to the port on which your web server accepts incoming requests.

grammar refers to one of two FileMaker XML grammars: FMPXMLRESULT or FMPXMLLAYOUT. Only the first of these grammars is available via XML export; the second is available only via Custom Web Publishing.

query-string refers to a series of one or more specific pieces of information you pass to the Web Publishing Engine to form the substance of your request. Among the pieces of information you would pass in the query string are the name of the database to access, the name of the layout you want to work with, and the name of a database action (such as “find all records,” expressed in the sample URL by the -findall command).

In general, then, you’ll use specially formatted URLs to access FileMaker data as XML via Custom Web Publishing. These URLs can be manually entered in a web browser, they can be linked from a web page, or they can be used by other processes or applications that want to consume FileMaker data as XML.

Understanding Query Strings

A lot of the action in a Custom Web Publishing URL occurs inside the query string—that odd-looking set of commands at the end of the URL. Here again is the sample URL from the previous section:

http://192.168.100.101/fmi/xml/fmresultset.xml?-db=Animal&-lay=web&-findall

The query string is the portion of the URL that comes after the question mark. A query string consists of multiple name-value pairs, with each name-value pair taking the form name=value. If there are multiple name-value pairs in a URL, an ampersand character (&) separates additional pairs from the first one.


Image Note

Query strings are not peculiar to FileMaker or to Custom Web Publishing; they’re an HTTP standard for passing information to a server-side program via a URL.


The sample URL passes three name-value pairs. Table 25.1 shows the names and their corresponding values.

Table 25.1. Name-Value Pairs in a Sample CWP URL

Image

In general, any Custom Web Publishing URL has to specify at least a database name, a layout name, and a database action to perform. In fact, you can omit the database name and layout name in the case of a few specialized database actions. But, at a minimum, you will usually provide a -db value, a -lay value, and the name of some database action.

A few more notes on query string syntax: The order of the name-value pairs within the query string doesn’t matter, as long as all the required pairs are present. The initial dash (-) in the various names is significant, however, and can’t be omitted. You’ll notice that the database action consists of a name without a value (which is perfectly legitimate in an HTTP URL query string); database actions always consist of a name with no value attached.

Image If you have spaces in your field, layout, or database names, this might cause trouble. SeeDealing with Spaces” in the “Troubleshooting” section at the end of this chapter.

Performing Specific Searches with CWP URLs

The CWP URLs we’ve looked at so far are simply querying a FileMaker database table, finding all records, and returning the results as raw XML according to the selected XML grammar. But what if you want to query different tables within the chosen database, or select only certain records rather than all records, or apply a sort order to the results? All these things are possible with CWP.

Specifying the Table

One of the reasons it’s so important to supply a layout name with your CWP URLs (via the -lay parameter) is that the active table is determined by the active layout, via that layout’s table context. You might recall that there’s a Show Records From option in the Layout Setup dialog for each layout. This enables you to select a table occurrence that will provide the layout’s table context. When you specify a layout in a CWP URL, you are implicitly setting the active table as well. All commands in the query string are considered to be applied to whatever table underlies the chosen layout.

Finding Specific Records

The Custom Web Publishing URL can also be used to search for specific records. To do this, use -find as the database action, instead of -findall. You also need to specify one or more search criteria, which are also supplied as name-value pairs.


Image Note

The database in question has only a single table, also called Animal, and that table is the table context for the web layout.


For example, if you’re working with a database of animals, and there’s a name field for the animal’s name, you can use the following URL to search for any animals named Hector:

http://192.168.100.101/fmi/xml/fmresultset.xml?-db=animal&-lay=web &name=Hector&-find

This code snippet specifies a database action of -find and adds one more parameter to the query string. We say name=Hector to cause the Web Publishing Engine to search for only records where the name is Hector. If there are any such records, they’ll be returned in the chosen XML grammar. If there are no matching records, we get back a response that looks a bit like Listing 25.2.

Listing 25.2. Sample Error Response

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE fmresultset (View Source for full doctype...)>
<fmresultset xmlns="http://www.filemaker.com/xml/fmresultset" version="1.0">
    <error code="401" />
    <product build="12/10/2003" name="FileMaker Web Publishing Engine" version="7.0v1" />
    <datasource database="" date-format="" layout="" table="" time-format="" total-count="0" />
    <metadata />
    <resultset count="0" fetch-size="0" />
</fmresultset>

You can see that in the case where no records are found, the XML returned by the Web Publishing Engine contains an error code appropriate to the situation. In this case, the code is a standard “no records found” error. Note that the exact format of the error response varies depending on which XML grammar you specified in the URL.

Specifying an Exact Match When Searching

In the previous example, the search appeared to be for all animals named Hector. This is not exactly true. The previous URL will have exactly the same effect as entering Find mode in the regular FileMaker client, typing Hector into the name field, and performing the search. FileMaker, when searching text fields, searches on a “starts with” basis, so this search actually finds animals named Hector, Hector II, Hectorax, and so on. To specify that you want an exact match, rather than a “starts with” match, you need a bit more precision. In FileMaker’s regular Find mode, you’d type =Hector in the search field, with the equal sign indicating an exact match. In a CWP URL, you would write the following:

http://192.168.100.101/fmi/xml/fmresultset.xml?-db=animal&-lay=web&name=Hector &name.op=eq&-find

Another parameter has been added to the query string here. The new parameter specifies what kind of operator we want to apply to one of the search fields. The syntax for this new parameter is

<field-name>.op=<operator>


Image Note

The operators available to you in Custom Web Publishing are similar to, but not identical to, the list you would find in the FileMaker client if you entered Find mode and clicked the Operators drop-down menu in the Status toolbar. Both FileMaker Find mode and the Custom Web Publishing find syntax contain operators unavailable in the other. Table 25.2 lists all the operators available in Custom Web Publishing.

Table 25.2. Comparison Operators for the -find Command

Image

Here, field-name is the field to which you want to apply the operator, and operator is a short character string indicating one of nine different possible operators. Here, the operator we’ve chosen is eq for an exact match. Other possible operators are cn for contains, bw for begins with (the default), and ew for ends with. So, if you wanted to find all animals with a name ending in tor, you could use this URL:

http://192.168.100.101/fmi/xml/fmresultset.xml?-db=animal&-lay=web&name=tor&name.op=ew&-find

This query string instructs the Web Publishing Engine to treat the search on the name field as an “ends with” search.

Performing a Numerical Comparison Search

Consider a database that contains some numerical fields. The Animal database used as an example so far contains a field called weight_birth for an animal’s birth weight. Suppose that you want to find all animals with a birth weight less than 100 pounds. The following URL would do it:

http://127.0.0.1/fmi/xml/fmresultset.xml?-db=animal&-lay=web&weight_birth=100 &weight_birth.op=lt&-find

Here, 100 is specified for the weight_birth search field, but we go on to say that the operator for that search field is the less-than operator, symbolized by the code lt.

Searching on Multiple Criteria

Suppose that you want to construct a more narrowly tailored search. You want to find all male animals with a birth weight less than 100. This is the equivalent of filling in two fields in FileMaker’s Find mode, instead of just one. You would use a URL like the following:

http://127.0.0.1/fmi/xml/fmresultset.xml?-db=animal&-lay=web&weight_birth=100&gender=Male&weight_birth.op=lt&-find

Here, we’ve simply added one more search field: gender=Male. This constitutes a further limit on the search you saw in the previous example. This search finds only records for male animals with a birth weight less than 100.

Creating Multiple Find Requests

The preceding example showed how to use multiple criteria to narrow a search. But what if you want to use multiple criteria to broaden a search? We’ve searched for animals with a birth weight less than 100. What if you also want to find, in the same search, any animals that have a current weight less than 500? You might recognize this as the equivalent of creating additional Find requests in the regular FileMaker Pro software.

To explain this kind of search, we need to introduce the concept of a logical operator. In the search demonstrated previously, for a record to be included in the search, all the search criteria in the query string had to be true. That is, an animal would not be included in the search results unless it was both male and had a birth weight less than 100. This kind of search is therefore often referred to as an and search or an all-true search.

On the other hand, when you think about also finding animals with a current weight less than 500, you have a situation in which an animal will be included in the search results if any of the search criteria are true. In other words, a record will be found if the animal had a birth weight of less than 100 or it has a current weight of less than 500. This type of search is thus often called an or search or an any-true search.

By default, the Web Publishing Engine treats all searches as and searches. To perform an or search, you use a URL like this one:

http://127.0.0.1/fmi/xml/fmresultset.xml?-db=animal&-lay=web&weight_birth=100&weight_current=500e&weight_birth.op=lt&weight_current.op=lt&-lop=or&-find

Here, you supply two search criteria. You also have to supply the field-level operator for each search field. In both cases, you’re performing a less-than search, so you need to specify an operator of lt for each field. The new element in the query string is the -lop parameter, which stands for logical operator. -lop can have a value of and (the default) or or (the one used here). The -lop parameter here instructs the Web Publishing Engine to treat the search as an or search.


Image Note

In FileMaker proper, you can construct a search that’s a complex mixture of and and or searches by entering multiple Find requests, each with more than one field filled in. Such searches can’t readily be reproduced with Custom Web Publishing: The -lop command can be applied only to all the search fields taken together. There is also no way to invoke the additional FileMaker search options of Constrain or Extend Found Set.


Specifying a Sort Order for Search Results

When you make a request to the Web Publishing Engine, you can specify how the results should be sorted. You can specify one or more fields to sort on, as you can in the regular FileMaker application, and you can specify whether each sort field should be sorted in ascending or descending order. Consider a URL that will find all records in the Animal table and ask that the records be sorted by name:

http://192.168.101.100/fmi/xml/fmresultset.xml?-db=Animal&-lay=web&-sortfield.1=name&-findall

The new query string command here is called -sortfield. You’ll notice we also added the suffix .1 to this parameter. This indicates the sort field’s precedence. The concept of precedence is meaningful only if you have more than one sort field, as you’ll see in a moment. Despite this fact, you can’t omit the sort precedence, even for a one-item sort; otherwise, the records won’t be sorted at all.

Suppose that you wanted to sort the records by gender and to sort within each gender by current weight from highest to lowest. You would do that like this:

http://127.0.0.1/fmi/xml/fmresultset.xml?-db=Animal&-lay=web&-sortfield.1=gender&-sortfield.2=weight_current&-sortorder.2=descend&-findall

Here, two sort fields are specified. The first sort is by gender, the second by weight_current. There’s also a new parameter, called -sortorder. Like -sortfield, -sortorder also takes a numeric suffix. Here, it’s used to indicate which sort field is being referred to. By default, each field will be sorted in ascending order. If you supply a value of descend for the second sort field, you ensure that the animals will be sorted, within each gender group, from heaviest to lightest.

Applications of Custom Web Publishing with XML

The preceding sections show how to use the Web Publishing Engine to query a database and publish the results as raw XML in one of several XML grammars. But what use is this capability, exactly?

Well, the most obvious significant use is to allow FileMaker to act as a web service provider. If you provide a web service client with an appropriate URL, remote services and programs can query your FileMaker database via the Web Publishing Engine and extract whatever information you choose to let them see.

Other Query Parameters

In addition to a single database command, Custom Web Publishing URLs can contain other parameters. Some are mandatory, such as -db, and (generally) -lay and -grammar. Others, such as -lop and -sortfield, are particular to specific commands. Table 25.3 shows a list of the most important ones.

Table 25.3. Other Custom Web Publishing URL Parameters

Image
Image

About Sessions

If you’ve read Chapter 24, you’ve already encountered some discussion of the concept of sessions. To recap briefly: The connection between a web browser and the Web Publishing Engine is very much unlike the connection between a client copy of FileMaker and the FileMaker Server. FileMaker Server can at any time reach out and push data to any connected client. It knows at all times what its connected clients are, where they are in the system, and at what network address they can be found. A web server, by contrast, retains no memory of a client from one connection to the next.

This is not a good thing for database work! I need my website to remember the contents of my shopping cart as I shop around the site. This is possible only with session management. Session management is generally a middleware feature. Web programming languages such as PHP and JSP offer the programmer different means of managing sessions.

In general, under session management, each incoming web request is associated with a key of some kind. The key can be passed in the URL (if you’ve ever seen a long ugly string such as ?jsession=A9238Ajasdj9mAEd in a web URL, odds are you were looking at a session key), or it can be passed behind the scenes in an HTTP cookie. FileMaker’s Custom Web Publishing session implementation lets you choose between these two methods. Whatever the means, the middleware on the web server has a way of associating that key to other information about the client. In the shopping cart example, the key might hook up to a database record that stores the actual contents of your cart as you navigate around the site.

FileMaker’s Custom Web Publishing, like other middleware solutions, enables you to manage sessions for your users behind the scenes. You would use this capability any time you wanted to store important information about the user that would be carried from screen to screen. An experienced HTML programmer could get away with passing a lot of data from page to page via the URL or via an HTML form. But there are limits to the amount of data than can be passed by URL, and there are limits to the type of data that can be passed by either method—generally just plain text strings.

FileMaker’s session implementation is quite elegant because it allows you to pass around XML fragments behind the scenes. This allows for much richer data structures than you could pass with regular HTML.

Managing Sessions

In addition to passing around XML information by means of sessions, FileMaker’s session implementation allows you to keep track of the state of the FileMaker client session as well. Database sessions are an additional capability on top of regular session management. In addition to “sessionizing” user information of your choice, they enable you to keep track of FileMaker-specific information such as global fields or the current script state.

So, for example, if your stylesheets modify a global field and you have database sessions enabled, the global field retains its new value for the specific current user as that user navigates from page to page. Or, if you use a script to change some aspect of the user’s state (for example, by using the Re-login script step to change the user’s privileges), this state is maintained across sequential requests.

Session management is a large topic, and we don’t have space to do it justice. The FileMaker documentation helps you get a better grip on the specific functions and commands that Custom Web Publishing uses for session management. If you intend to make heavy use of global fields or call scripts from your stylesheets that would change the state of a user’s privileges, you should configure the Web Publishing Engine to enable database sessions.

Troubleshooting

Getting the Right Privileges

I can connect to my Web Publishing Engine and FileMaker Server via the Administration Console, but I don’t see the databases I expect to see.

Make sure that for every database you want to make available via XML-CWP, you have attached the appropriate extended privilege (fmxml) to at least one privilege set.

Dealing with Firewalls

My web requests mysteriously time out, as though something were blocking them.

If you can get to the Administration Console, but your Custom Web Publishing URL requests appear to get no response, you might have a firewall in your way. If you suspect a firewall might be involved, consult your network administrator to explore this question. If it turns out that your machines are set up such that your web server is on one side of a firewall and your Web Publishing Engine machine or FileMaker Server machine is on the other, you need to open certain ports in the firewall. Here are the rules:

• When the web server and Administration Console are on one machine and the Web Publishing Engine on another, traffic must be able to flow between the two machines on ports 16016 and 16018.

• When the Web Publishing Engine is on a different machine from FileMaker Server, traffic must be able to flow between the two machines on port 5003.

Dealing with Spaces

The Web Publishing Engine doesn’t seem to see my entire URL. I enter a long URL, and the web server appears to truncate it and reports that the shorter URL can’t be found.

If, despite the cautionary notes in this chapter, you have left any of your databases, fields, or layouts with spaces or any other nonalphanumeric characters in their names, your Custom Web Publishing URLs might very well break. If a web server or browser encounters a space in a URL, it might assume that the URL ends there. Other nonalphanumerics have different but equally irritating effects.

If you must work with URLs with spaces in them, you can get by with replacing all spaces with the string %20 whenever you need to write out a URL. Your stylesheet then might generate an HTML page with the following link:

<a href="http://192.168.101.100/fmi/xsl/process-this.xsl?-db=Too%20Many%20Spaces&-lay=Spaces%20Here%too&-findall


Image Tip

If at all possible, we strongly encourage you to use only alphanumeric characters for database, layout, and field names and to avoid the use of whitespace. Extend this caution to script names if you are planning to call scripts from the Web.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.235.144