I can display images from a folder, but I want to add tags like landscape or building and show only matching pictures. Can I do that without a database?
How can I tag images and filter a PHP gallery by tag?
Answers
Yes. For a small gallery, a JSON file is a straightforward place to keep the tags. Map each image filename to an array of tags, then have PHP read the file and loop over the entries that contain the selected tag.
You would need to add the filename and tags to the JSON when you add an image. Keeping the metadata separate also means you can change tags without renaming the image files.
Reply to this answer
Take a look at SQLite if you want to search and manage a larger collection. It stores the database in a file, so you don't need a separate database server.
You could have an images table, a tags table, and a table connecting images to tags. PHP can then query for images with a given tag. That's more setup than JSON, but SQL gives you a way to handle more complex searches without building all the filtering yourself.
Reply to this answer
You can also filter in the browser with JavaScript. Put the tags in data attributes on each image element, then show or hide elements when someone chooses a tag. That can make the filter feel immediate.
But the attributes still need to come from somewhere. If PHP is just scanning a folder, it won't know which tags to put on each image unless you also maintain that information in JSON, a database, or somewhere else.
Reply to this answer
For a very small project, filenames can do the job. Use a consistent naming pattern and split the filename in PHP to extract the tags. It's simple, but changing a tag means renaming the file, and you'll need rules for separators and tag names.
Reply to this answer
Another option is to store the tags in the image metadata and read them in PHP. That keeps the information with the image, which can be useful in other software too. Check that your image formats and tools support the metadata fields you choose before relying on it.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Related Discussions