Team LiB
Previous Section Next Section

Creating a File-Based Database

Before actually using the dba functions, you have to create a database file. This is done using the function dba_open(). Similar to PHP's fopen(), this function expects both a filename and a file mode. The third parameter is the name of the handler used. Listing 26.2 (dba_create.php) creates a file called dba.db and uses the handler provided in handler.inc.php. Upon success, the database is closed using dba_close().

Listing 26.2. The Include File for the dba Handler Used
<?php
  require_once "handler.inc.php";
  $dba = @dba_open("dba.db", "n", $dbahandler);
  if (!$dba) {
    echo "Failed creating database.";
  } else {
    echo "Succeeded creating database.";
    dba_close($dba);
  }
?>

NOTE

The PHP process needs write privileges to the database file and the directory it is residing in. In our examples, the .db file resides in the current directory, which also means that it could be remotely downloaded. In a production environment, this should be changed accordinglyfor example, by moving the .db file into another directory that is not accessible via Web browser/HTTP.


For the file mode, the following options are available:

  • c for read access, write access, database creation (not available for dbm and ndbm)

  • n for read access, write access, database creation, and truncation

  • r for read access

  • w for read access and write access

Only the modes c and n support creation of the database file.

Also, there are some options for file locking:

  • d for locking using the OS (default)

  • l for locking using a .lck file

  • - for no locking

  • t for testing the lock (additionally to d or l)

On the manual page for PHP's dba functions, http://php.net/dba, you will find an overview table that shows which locking modes let which write operations fail.

Because mode c is not supported by all dba handlers, Listing 26.2 uses mode n to create the database. This is usually a step that is done only once. Afterward, you will most probably use either read or write access and stick to the (more performance and reliable) modes r and w.

NOTE

Especially older Windows versions (Windows 98, Windows ME) do not support file locking at all; in this case, use no locking (option -) instead.


    Team LiB
    Previous Section Next Section