Beginning Steps

Before beginning with the tutorial, there are some introductory steps that are necessary.

Installing the Slim Framework

To begin, make surethat you have the Slim framework installed. If you do not, installation instructions can be found here. Return to this page when this step is completed.



Important information to keep in mind

By this point you should have the Slim Framework installed. Before we continue, there are a couple things that are good practices to keep in mind moving forward.

First, when accessing a database, it is often frowned upon to sign in using the root user. Users rarely need all of the privelages that the root user offers so we often create user that have access to only what they need. We will go through steps to create a limited user with access to the database we create.

Second, there are many ways to actually store images using MySQL and the Slim Framework but one way that should generally be avoided is storing the actual image in a database through Binary Large Objects (BLOBs). This is usually considered bad practice. You are consuming connections to the database, that are going to remain open longer, that could otherwise go to something that should be in the database. Also, another problem with storing BLOBs in a database is the increase in size it is going to add to your backups. Should you have to do a restore, it is going to take a lot longer to load up that giant sql backup you've taken because it has been inflated with blob data. If you would like to know more, there are many responses to this question online. In this tutorial, we will be storing URLs in a database and then accessing that URL through PHP to display that image to the browser. The test URL (and image) we will be using is displayed below.



http://images5.fanpop.com/image/photos/26300000/beautiful-emma-emma-watson-26334822-1131-707.jpg

Moving On

Now that we have all of the resources necessary, let's move on creating the user and the database.

Creating your user and database

Let's first create a simple SQL script named testScript.sql that will hold our image URL.



    CREATE database MMTest;
    USE MMTest;

    CREATE table imageURLs(
    id varchar(4) primary key,
    url varchar(2000));

    INSERT into imageURLs values(
    '1', 'http://images5.fanpop.com/image/photos/26300000/beautiful-emma-emma-watson-26334822-113
    1-707.jpg');
    

Here we have created a database called MMTest in which we have placed a table that is called imageURLs. Table imageURLs contains a primary key to give each URL a numerical ID, and the actual URL that the image originates from. It is possible to also add more attributes within the the table to further distinguish and describe different images. We can now run this script in MySQL with (you can use the root user for this command):


    mysql -u root -p <password> < testScript.sql;
    

Now that you have run your script, log into MySQL using this command:


    mysql -u root -p <password>;
    

We will now create a guest user that does not have access to everything. In MySQL type the following commands:


    CREATE USER '<user>'@'localhost' IDENTIFIED BY "<password>";
    

This will create a MySQL user named <user> with <password> as their password. Users in MySQL allow for you to regulate who has access to what parts of your database.


    GRANT SELECT ON MMTest.* TO <user>;
    

This will grant only the permissions to view the database to to the user that was created. You can set up your own permissions as they pertain to your project.

Congratulations! You now have a image (or rather a path to an image) stored in your database. This method is similar to accessing web servers however, some online file systems like Amazon Web Servers S3 (AWS S3), require a private key to access the images you upload. This requires a little more research to understand how private keys and public keys work, and how to actually implement them to access your file system online. This tutorial will not address this topic.



Implemeting this into the Slim Framework

Finally, we will now use the Slim Framework to display this image to the browser.

The next step is to define connection settings for the database in /src/settings.php. In the associative array called 'settings', add a key value pair for the database.




    'testImage' => [
        'username' => 'guest',
        'password' => '',
        'host' => 'localhost',
        'dbname' => 'MMTest',
        'db' => 'mysql',
    ],
    

Then, in /src/dependencies.php, define a new container for the database settings.


    $container['testImage'] = function ($c) { 
        $settings = $c->get('settings')['testImage'];

        $connString = $settings['db'] . ':host=' . $settings['host'];
        $connString .= ';dbname=' . $settings['dbname'] . ';charset=utf8mb4';

        $db = new PDO($connString, $settings['username'], $settings['password']);

        return $db;
    };
    

Next, we modify the /src/routes.php file to determine the endpoint for our URL and what the behavior of that endpoint is. In this case, the endpoint will be named /testImage.


    $app->get('/testImage', function ($request, $response, $args) {

        $db = $this->testImage;
        $strToReturn = '';

        foreach($db->query('SELECT * FROM imageURLs WHERE id = '1') as $row) {
            printf('<img src = "%s" /<br/>', $row['url']);
        };

        return;
    });
    

With this in place, it is now possible to view your image through your browser in the Slim Framework. Go into your browser and type "zero-to-slim.dev/testImage" and you should have your image displayed!