Posted by & filed under FileMaker, PHP.

The purpose of this lesson is to create a simple PHP page that will make a connection to a FileMaker database hosted on FileMaker Server and pull information that will be displayed as HTML on a webpage.  This will help you get started with the basics of using FileMaker Custom Web Publishing

Objectives:

  • Configure FileMaker Server for CWP access
  • Configure the database for CWP access
  • Create a PHP file which will read data from a database and display the result on a web page
  • Search for a record and display data from the found record
  • Mix HTML and PHP

Requirements:

  • Admin access to FileMaker Server
  • Text editor or a PHP IDE (Integrated Development Environment)
  • Web server with PHP installed

Configuring FileMaker Server

The first step to getting started with CWP is to make sure your FileMaker Server is properly configured.  To do this, you’ll need to log in to your FileMaker Server admin console.

First, make sure that the Web Publishing Engine is enabled.  Scroll down on the Status page and look for the Web Publishing engine option.  Click the slider button to the right of the Web Publishing Engine to enable it.  Look for the green checkmark circle which will indicate if the WPE is successfully running.

WPE Enabled

From there, select “Web Publishing” from the menu on the left.  Select the PHP tab and check the “Enable PHP Publishing” checkbox. This will enable your PHP application to connect and communicate with FileMaker Server.

PHP Publishing Enabled

With the server properly configured for CWP we’re ready to move on to the FileMaker database

Configure the FileMaker Database

In addition to configuring the FileMaker Server for CWP we also need to make sure that our FileMaker Database is ready for access through CWP.  Create a new database and upload it to your FileMaker Server.  I’m going to name my database “Test Database” for this example.

Open the Manage Security dialog and create a user to be used for accessing the database through CWP.  For this example I’m going to create a user named “PHP User” which will be used only for accessing the database through CWP and give this user the [Data Entry Only] privilege set.

Go to the privilege sets tab of the Manage Security window and select the privilege set assigned to your newly created user.  Click Edit and enable the Access via PHP Web Publishing extended privilege set by clicking the checkbox next to it.  Press OK and close the Manage Security window to save your changes.

fmphp-enabled

After making this change you should be able to see that PHP access is enabled for your database from the FileMaker Server admin console.  Check the activity tab and you will see a dot in under the PHP column for your database if you have correctly followed the previous.  This dot indicates that at least one privilege set for the database has the fmphp extended privilege set enabled and that we’re ready to connect to it using PHP.

admin-console-dot

Create a table called “People” in this new database with _kp_ID (primary key), Name, and Favorite Color fields.  Also create layout called “PHP Test” with these fields on the layout.  Create some records and set some values in the name and color fields for testing your work.

table layout

IMPORTANT: Only fields placed on the layout can be accessed through the PHP API.  If you don’t have the field on the layout you won’t be able to get data from it in your PHP code. Be sure to include any fields you want to get or set the values of on your layout.

Setting up the web server

With HTML you’re able to write some code in a text file, save is as an .html file, and then open it in a web browser and see the result.  PHP is different from HTML in that it is code that needs to be executed, rather than just markup that gets read by your browser and displayed as a webpage.  Because of this difference we need to run the code on a web server and can’t just double-click the file to see our work.

You can use any web server with PHP installed to run your code.  Some options you may want to consider are:

• FileMaker Server with Web Publishing enabled
• A server provided by a web hosting company where you can upload files
• On your machine by running a web server

For this tutorial I’ll be using the third option.  I like to use an AMP (Apache MySQL PHP) program for development and testing, as it makes it easy to manage the server.  MAMP (Mac Apache MySQL PHP) or WAMP (Windows Apache MySQL PHP) are free and easy to setup and configure on your local machine. These programs run a web server, php, and a MySQL database server on your computer with minimal setup and configuration, which for our purposes makes it so that you don’t have to worry about uploading or transferring files after you make a change in your code before you can see what the change does.

Download and install MAMP/WAMP (xAMP) and follow the setup options and start the Apache web server through the xAMP console.  Find the web root directory for the new web server running on your machine, which will probably be called htdocs will be located in your xAMP installation directory.  This is where we’ll be putting our files so that they show up on our new web server.  If you’re running xAMP on your local machine you should be able to see the start page by going to http://localhost:8888/ in your browser (this can also be changed to use port 80 in the xAMP console).

Put the FileMaker API on the server

Now that we have our server set up we’re ready to install the FileMaker API.  The first thing we’re going to need to do is grab the FileMaker PHP API (Application Programming Interface) from our FileMaker Server installation.  The PHP API is a set of PHP files that we will use with our code to make the connection to FileMaker Server.

The PHP API is located at:

  • Windws – drive:\Program Files\FileMaker\FileMaker Server\Web Publishing\FM_API_for_PHP_Standalone.zip
  • Mac – /Library/FileMaker Server/Web Publishing/FM_API_for_PHP_Standalone.zip

Copy the zip file to your computer, extract it, and put the extracted files in your web root.  The files should look like this:

api-root

Note: Normally you would put this in what is called an “includes” directory, but we’re going for a quick tutorial of how to get connected. Working with includes folders makes configuration a bit more challenging, so we’re going to skip it for now.

Pick your editor

Writing PHP code can be done in any text editing application, such as Notepad or TextEdit, but there are lots of applications that will help you write your code with features like automatic code completion or code highlighting to help you better see the organization of your code.

There are also more advanced programs which will help you manage files, offer version control, and will spot errors and make recommendations about best practices while you’re writing your code.  They can even help you debug your code in a way similar to the script debugger and data viewer in FileMaker.  These programs are great for coding, but they take a bit of setup work to get everything running.

I recommend installing one of these code editor programs to help make your job easier while writing code:

Simple, free code editors

Integrated Development Environment (IDE) programs

  • IntelliJ (free for personal use)
  • PHPStorm (paid, almost exactly the same as IntelliJ for PHP but cheaper to buy)

Let’s start coding!

With everything in place we’re ready to start writing our code.  Create a new file in editor and save it in your web root as fmdemo.php (in the same directory as filemaker.php. You can name your file anything you like, but give it the .php extension to help the server see that we’re going to be using PHP code in this file.

The first thing to do is to show our web server that the code we’re writing is PHP code.  This is done using the PHP tags.

Any code we write in-between these tags will be executed as PHP code on the server and won’t be seen by the client’s browser.

Now, tell the server we’re going to be using the FileMaker PHP API and let it know where to find the classes we’ll be referencing.  This sets us up for making calls to it in the next few steps

Now, we can set up our connection to FileMaker Server.  The four parameters for the function we’re going to call are in order:

Database name
Server address
Username
password

Let’s prepare to get a random record from our People table.  To do this we’ll use the findAnyCommand method, which does exactly that.  This method takes a single parameter, which is the name layout to pull the record from.

Now we can execute the find we’re prepared and set the result to a variable

A result from the FileMaker PHP Api will either return a FileMaker_Error object if there is an error or an FileMaker_Result object, which contains an array of records (even if there’s really only one in the result).  It’s important to always check for errors when there is a possibility of getting one, and then handling the error appropriately.  We’ll do this by adding in an if statement to check to see if our result is an error, and then write out the error message before exiting our script since we can’t do anything else useful right now to better handle the error.

If we didn’t get an error we’re able to view our results and print out some of our fields.  Use the getFirstRecord and getFieldName methods to store the first record in a variable and then read a field value from the record.  I’ll retrieve the Name field from the People record that was returned and write it out using the echo function.

Try loading this page in your browser now by going to http://localhost:8888/fmdemo.php (use the correct address of your server if it isn’t localhost:8888).  If everything was done correctly you should see one of the values from the Name field that you entered in your database.  Since we’re using the findAnyCommand method the value will be randomly selected from one of the records in your database, so it will change every time you reload the page.

Find a specific record

Let’s modify our code a little bit to find a specific person and display their name and favorite color.  We can use the findCommand method instead of findAnyCommand to create a find request just like we would in FileMaker.  We’ll also add a addFindCriterion call to the $findCommand object to specify the field we’re going to search on, also very similar to a FileMaker script.

It’s important to set a “range” value here, which will limit the maximum number of records returned.  If you don’t limit the range and your found set is very large it could make your code very slow or even possibly cause your script to crash due to your server running out of memory.  Set a range using the setRange method, which takes two parameters – a number of records to skip and a number of records to return in the result.  Set these to 0 and 1 for now to not skip any records and only return one record in your result.

Finally, let’s show both the person’s name and their favorite color at the same time by changing our echo at the bottom of our code.  I’m also going to assign the values to a variable before echoing them out to make it a bit easier to read what the echo statement should be writing.  PHP will actually evaluate variables that are placed inside double quotes, so you don’t have to worry about concatenation in this case.

Mix your HTML and PHP

You can mix HTML and PHP on a page to make a webpage with dynamic data from your database.  HTML can be placed outside of the <?PHP ?> tags and will be sent to the browser like normal.  You can also have multiple PHP tags on the page to mix your code and your HTML as needed.

That should cover the basics for using FileMaker CWP.  Let me know if this has been useful for you, or what you would like to see from me in the future.  Be sure to share this article using the buttons below if you think this would be helpful for other people as well.

Share
  • Higinio Fuentes

    THANK YOU VERY MUCH!
    I’m looking for this info for a week now!
    I have a doubt, the Database name
    Server address is the same address I use to open the database with fm remote?

    • If you’re using a single-machine deployment of FileMaker Server, then yes, you would use the same address you use for the Open Remote option. On a multi-machine deployment of FileMaker Server the WPE would probably have a different address.

      • Higinio Fuentes

        Hi David,

        Thank you for your advice, now is going smothly. Thank you very much for your explanations.

        I have a single machine deployment, but the time of charging and presenting 376 records with 5 fields and no portals takes 15 seconds!

        I think is quicker if I go the ODBC side with mysql, what do you think?
        Or you have a trick as well to improve speed?

        Thank you again for your article and advice

        Higinio
        Le 31 10 14[44] 18:55, Disqus a écrit :

        • MySQL is definitely a faster database platform than FileMaker in general, but I think the real issue here is your query size.

          Rather than displaying so many records I would recommend using the setRange() function to limit how many results you get at a time, and splitting your results into multiple pages. You could show 20 results per page, for example, and let your users page through results.

          • Higinio Fuentes

            Hi David,
            I have reduced the presentation time thank to your suggestion of setRange(), but over all thank to create a new FM db who only take the tables needed with remote connection link.

            Thx again!

  • Justin Close

    Hey David,
    Thanks for the nice article. Do you have any experience with installing FMS 13 (on Windows server 2012) alongside WAMP, so that it uses Apache instead of IIS? (The FMS 13 installer instructions say that it installs and configures IIS if it can’t find it.)

    Thanks,
    Justin

    • I haven’t, but if you were going to do it I would guess that you would need to deploy it to IIS first and then do some significant modifications, which might very well lead to issues.

      A safer alternative with less hack-ey solution might be to deploy FMS to IIS as normal, and then forward your other traffic through ISS to your Apache deployment (running on a different port) using the IIS Server Farms options.

  • James

    Hi David

    Thank you for this detail and concise information on this topic. I have few questions to ask your expertise:

    1. Do I need to install MAMP or whatever I have existing is sufficient?
    2. Can you explain a little more about the INCLUDE? I am confuse with the directory structure.
    3. If I use CWP with FileMaker as the backend database, can I still use the layout I have in FileMaker or I need to design and create a totally different layout?

    Thank you in advance.
    James

    • 1. No, but it’s useful for testing and doing development before you deploy to a live server. Macs have Apache built-in already, so you don’t have to use MAMP (Mac Apache MySQL PHP), but it does make it easy to configure and setup multiple sites with the pro version.

      2. W3 has some good information about how include and require work, but in a nutshell it inserts the code from the other files, which allows you to call functions written other places.

      http://www.w3schools.com/php/php_includes.asp

      Like other paths you might write, “/” means root, “~/” is home, “./” is current directory, “../” is up one directory, etc, etc. No slashes or dots means to look in the current folder or any server/site-wide configured “include” folders for the file you’re looking for.

      3. There isn’t a way to get the GUI part of your FileMaker layout outside of FIleMaker (other than WebDirect which is a different FM technology). You do, however, need to have the fields you want to access with PHP on your layout, since you’re essentially querying the layout as a table, rather than the base table directly. Any fields not on the layout will be inaccessible. It’s generally a good idea to use web-specific layouts so that you can have only the minimum required fields and so that you don’t accidentally change something you need when working on a UI.

  • Frank NTWARI

    Hey David,

    really nice article, i tried the same using MAMP on the localhost network and it works perfectly! So i have tried to host it on server provided by a web hosting company where i uploaded files of my php solution (which was option two in this tutorial regarding web servers), and specified well the IP address of the server where Filemaker Server is installed, but i can’t get any result as on the local network. if you could help with any idea it will be great! thanks

    • This is either a firewall or network issue. Check and make sure your ports are open and that the FileMaker server is accessible at the address you’ve used in your PHP. If your filemaker server is behind a router and doesn’t have a dedicated public IP you may be unintentionally reaching another computer on your network instead of FMS.

  • Bill Clarke

    I’m replacing a ColdFusion/MySQL app with what I hope will be a Pro solution for the admin of the content, and a PHP-FM Server public facing web app. How much slower is FM Server than PHP-MySQL, assuming everything is well written and optimized? I just don’t want to build something that will perform worse than their current solution. 🙂

    • FileMaker Server’s performance is pretty good after FMS 12, where significant improvements were made to the web publishing engine. You’ll definitely want to use a two-machine deployment for anything more than minor traffic. Performance is pretty good in my experience, though I can’t give you any hard numbers. I haven’t had it be a problem in the past as long as the server machine and bandwidth were up to it. I’ve replaced some MySQL solutions with FileMaker and been satisfied enough and haven’t noticed any significant performance differences, though I haven’t timed the queries to see how things actually measure up.

      FileMaker supports up to 2000 simultaneous CWP connections, which is really 2000 queries, not 2000 users, and so it can perform well for a decent amount of activity. It doesn’t scale up past that though, so if you’re expecting high activity it won’t be the right solution.

      • Bill Clarke

        Perfect. Thanks David!

  • awesomeinbread

    I keep getting an error “Layout is missing” Any ideas?

    • Every query has to be done on a FileMaker layout. Make sure your layout name is spelled correctly, and that you don’t have any extra spaces or anything like that in your layout name in PHP or in FileMaker. Also, the user you are authenticating with must have permission to view that layout, so double-check your user permissions as well.

    • oamih

      Make sure the parameter for something like newFindAnyCommand() is the layout name.

      $layout_name = ‘PHP Test’;
      $findCommand = $fm->newFindCommand($layout_name);

  • chets dev

    how to get below details to connect ?

    Database name, Server address, Username, password

    • That would be the same information you use to log in through FileMaker Pro, though I would recommend creating a user which is used exclusively for CWP/PHP and has a restricted permission set to prevent potential exploitation.

  • Morten Hansen

    Hey guys

    I hope there can help me.

    How to insert data from a contener with external store in my php code?

    And thanks for a very helpful block

    • You can’t insert container data directly through PHP or XML, but there are a few alternatives.

      One solution is to base64 encode your data, post it to a text field, and then run a script to decode the text back to container data and insert it into the container field.

      Another solution is to save the file you eventually want in a container field to a directory on your server using PHP. From there, you can trigger a script on the server to insert the file into a container. The BaseElements plugin is a good way to handle this, as it allows inserting container data from other directories beyond what FileMaker Server natively supports.