To show you how to integrate the Kumulos PHP library into a website, this tutorial will guide you through making a simple application to store users with a mugshot (photo). The website can then show a user by username with their mugshot.

To follow along, you’ll probably want to watch the MugShot video (below), and download the PHP code we’ll be using.


Specification

Here’s an outline of the web ‘application’ we’re going to build for our Kumulos app.

  • Users register with a username, password, and mugshot image
  • Users can be viewed by username, with their mugshot image

So, let’s get started!


Kumulos Integration

To begin with, we create a wrapper class called Kumulos to include anywhere we want to use Kumulos from our website. This class wraps up the kAPI class and gives us a central point of configuration.

Kumulos.php

<?php

require_once 'lib/libKumulos.php';
// Your API Key should go in here
define('K_API_KEY', 'YOUR API KEY HERE');

// Your secret key should go here
define('K_SECRET_KEY', 'YOUR SECRET KEY HERE');

final class Kumulos {
    private static $k;

    public static function api() {
        return (isset(self::$k) && self::$k instanceof kAPI)
            ? self::$k
            : self::$k = new kAPI(K_API_KEY, K_SECRET_KEY);
    }
}

You’ll need to fill in the values of the K_API_KEY and K_SECRET_KEY constants.

Now getting Kumulos set up in your app is as simple as including the file like so:

require_once 'Kumulos.php';

User registration form

Our website will allow users to register a username, password, and mugshot by uploading a file. The HTML to achieve this is listed here:

index.php

<!DOCTYPE html>
<html>
    <head>
        <title>MugShot - Kumulos PHP Tutorial</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    </head>
    <body>
        <h1>MugShot</h1>
        <fieldset>
            <legend>Register Now!</legend>
            <form action="" method="post" enctype="multipart/form-data">
                <label>Username</label>
                <input type="text" name="user[username]" />
                <label>Password</label>
                <input type="password" name="user[password]" />
                <label>Mugshot</label>
                <input type="file" name="mugshot" />
                <input type="submit" name="submit" value="Register!" />
            </form>
        </fieldset>
    </body>
</html>

Handling the registration

When the form above is submitted to the server, we need to process it and call the Kumulos API we set up in the video to create a new user.

index.php

<?php

require_once 'Kumulos.php';

// Registering a new user
if (isset($_POST['submit'])) {
    $userData = $_POST['user'];
    $userData['username'] = htmlspecialchars($userData['username']); // Should do proper validation/sanitisation of all user-submitted data
    $userData['password'] = sha1($userData['password']); // Hash the password

    // Handle the upload
    if ($_FILES['mugshot']['error'] === UPLOAD_ERR_OK) {
        $userData['imageData'] = base64_encode(file_get_contents($_FILES['mugshot']['tmp_name']));
    }
    else {
        die($_FILES['mugshot']['error']);
    }

    // Call Kumulos
    try {
        // Create the new user
        $newUserID = Kumulos::api()->call('createUser', $userData);

        // Redirect to the view user page
        header('Location: viewUser.php?username=' . urlencode($userData['username']));
    }

    // Handle errors
    catch (kAPIException $e) {
        die($e->getMessage());
    }
}

The crucial line there is:

    $newUserID = Kumulos::api()->call('createUser', $userData);

That calls the createUser API method on Kumulos with the array of parameters stored in $userData. If all goes well, it will return a new user ID.

Of interest is the way that the file upload is handled. Because Kumulos stores the imageData in a data field, the file’s contents must be base64 encoded before calling the API method.

After registering, we redirect to the view user page and show the user’s mugshot.

View mugshot

The page to view a user starts by calling the Kumulos API method to retrieve the user record, and then it displays the user record in HTML.

viewUser.php

<?php

require_once 'Kumulos.php';

// Viewing a user
if (isset($_GET['username'])) {
    // Call Kumulos
    try {
        // Get the user by username with mugshot
        $users = Kumulos::api()->call('getUserWithMugshot', array(
            'username' => $_GET['username']
        ));
    }
    // Handle errors
    catch (kAPIException $e) {
        die($e->getMessage());
    }
}

This code calls the API method we set up to get a user with their mugshot, searching by their username. When it completes, the $users variable should contain an array with our user in it.

Displaying the User

<!DOCTYPE html>
<html>
    <head>
        <title>MugShot - Kumulos PHP Tutorial</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    </head>

    <body>
        <h1>MugShot</h1>
        <?php
        // Loop through the results array (although there should only be one result in it)
        foreach ($users as $user):
        ?>
        <h3>User: <?php echo $user->username; ?></h3>
        <img src="data:image/png;base64,<?php echo $user->mugShot->imageData; ?>" alt="User Mugshot" />
        <?php endforeach; ?>
    </body>
</html>

Here we can see that the $users array is looped through in a foreach loop. The code inside the loop prints out the details of the user.

Because the imageData from the mugShot is base64 encoded, we can display it in an image tag by using the data protocol. We specify a MIME type, the encoding of the data, and then the data itself.

Limitations

Here are a few of the limitations to this example:

  • Only PNG images will be displayed correctly because of the hard coded MIME type in the img tag
  • Error handling is pretty basic
  • Usernames are not checked for availability before registration
  • User input sanitization is pretty basic

Summary

Of course this is a trivial example of how to integrate Kumulos, but it does demonstrate the key integration points.

For production use, we would recommend using a PHP framework such as CodeIgniter, CakePHP, or Zend Framework to handle the request processing, input validation/sanitization, and templating. However, for quick and dirty integrations, the code here should suffice.