Search code examples
phpdatabasefilesystemsphoto-gallery

How to create a proper photo album application in PHP?


I've worked with photo albums before, and I've found 2 methods of managing them through PHP:

  1. Store the images in the database or
  2. Store them in the filesystem

Each has its own advantages and disadvantages.

With the database, I can store the time of the upload, where it was uploaded from, etc. It's harder to do something like that with the filesystem (like a manifest.json file for non-file related data).

But with the filesystem, it just feels nicer for some reason, because, you know, photos are images, and are meant to be stored in a filesystem. Just feels right.

But what is the proper way of making a photo album that displays things like:

  1. The photo (of course)
  2. The time it was uploaded
  3. Who you are with/want to tag (or a general caption)

etc.

What is the RIGHT way of going about this?


Solution

  • One way you can store all of the information, and using the file system for the images is by combining the two!

    If you have a table containing a list of the images, each with the images filename, the time it was uploaded, and a caption.

    Then, you could write a simple class like below to manage each image:

    class Image {
        private $info;
        public function __construct(int $id, $mysqli) {
            $info = $mysqli->query("SELECT * FROM `images` WHERE `id`=" . $id);
            $this->info = array();
            $this->info["id"] = $info["id"];
            $this->info["src"] = "/my/path/" . $info["name"] . "." . $info["type"];
            $this->info["upload"] = strtotime($info["upload"]);
            $this->info["tags"] = json_decode($info["tags"], true);
        }
    
        public function Id() { return $this->info["id"]; }
        public function Src() { return $this->info["src"]; }
        public function Upload() { return $this->info["upload"]; }
        public function Tags() { return $this->info["tags"]; }
    }
    

    This simple class would work if you have a table in your database like this:

    +----------------------------------+------------+-----------+-----------------+-------------+
    | id INT NOT NULL AUTO_INCREMENT   | name TEXT  | type TEXT | upload DATETIME | tags TEXT   |
    +----------------------------------+------------+-----------+-----------------+-------------+
    

    So now, if you know the ID of the image you want to get, you can get it with the following code:

    $id = 57;
    $img = new Image($id, $connection);
    

    Now we can get information on the image!

    echo $img->Id() // output: 57
    echo $img->Src() // output: /my/path/image.png
    echo $img->Upload() // output: 1375858084
    

    The Tags() function will return an array, JSON decoded from the column in the database.