Image moderation with PHP and Twig

In this article we will see how we can moderate images automatically with PHP and the Twig template engine.

We are going to create a small application that lets users upload images and check if those images contain inappropriate content.

Before we get started, we will have to make sure we have all dependencies installed. Two dependencies will be needed to create our application.

  • Twig: Template engine for PHP
  • Sightengine: The SDK that will allow us to automatically moderate our images
composer require "twig/twig:^2.0" "sightengine/client-php"

1# Create the web server

Let’s start out by creating the server with an app.php file:

In a second step we will create a folder called templates with an index.html file inside.

2# Upload your images

The first step is to create an upload folder. This folder will be used to store our images.

The second step is to modify our server. The images will be automatically sent to the upload folder we created before.

We will also modify our index.html file to add a form for file upload.

3# Moderate the images with Sightengine

Sightengine is an API that allows you to moderate image. There are 8 models currently available.

  • Nudity detection (i.e. detect adult or suggestive content)
  • Weapons/Alcohol/Drugs detection
  • Face/People detection (i.e. detect if the image contains a person or several people or nobody, along with the positions of those faces)
  • Face Attributes detection (get the age group and gender, determine if a face is covered with sunglasses…)
  • Celebrity detection
  • Image type detection (i.e. detect if the image is a natural photograph or an illustration)
  • Image Properties (i.e. determine the quality of an image along with its main colors)
  • Scammer detection (detect if an image is likely to have been submitted by a romance scammer)

You must first register on Sightengine’s website, it’s totally free. Just click on the get started button and create an account.

Once logged in, click on the get started page. Sightengine works with two keys, we will need these keys to use the SDK in our application. Be careful, do not share them, they are secret keys.

For the purpose of this tutorial, we will activate the nudity, scammer, celebrity, minor and inappropriate content (drugs, alcohol, weapons) models.

You might want to add or remove some of those models depending on your specific needs.

The API is simple to use. Here is an example output:

We will modify our server to add the Sightengine SDK. If the moderation succeeded, the image will be uploaded otherwise an error message will be displayed.

We will then add the data returned by the server into our index.html file.

# Final thoughts

I hope this was helpful. If you want to know more about Sightengine you can try their demo. Feel free to share and recommend if useful :)