Laravel + AWS Rekognition SDK Integration

This project demonstrates the integration of the AWS SDK for PHP Rekognition client into a Laravel project, covering two functions of the Rekognition service: detecting text in photos, and detecting nudity. This project is a demonstration and requires you to integrate your own use case.

View Demo

View on GitHub


Prerequisites

AWS Account & Access Keys

You will need to get your AWS Secret Access Key and Access Key ID to use the SDK. Click here to visit the Managing Access Keys for IAM Users page and learn how to find these keys.

Knowledge of Rekognition

It is important for you to know what the Rekognition offers, how we should present requests, and how we should expect to receive requests. Rekognition offers many features that are not included in the project.


Installation

Begin by installing the AWS SDK for PHP package with Composer. Edit your composer.json file to require aws/aws-sdk-php version 3.

"require": {
"aws/aws-sdk-php": "3.*"
}

Then update your project by running this command in your terminal at your project root.

composer update

Configuration

Add two new environment variables to your .env file and populate the values with your keys found in the prerequisites section.

AWS_SECRET_ACCESS_KEY=ENTER_YOUR_KEY
AWS_ACCESS_KEY_ID=ENTER_YOUR_KEY

Usage

Create the Client

Create a new RekognitionClient and fill in your region to begin making requests.

use Aws\Rekognition\RekognitionClient;
$client = new RekognitionClient([
'region' => 'ENTER_YOUR_REGION',
'version' => 'latest'
]);

Preparing the Image

Pass the image as base64-encoded image bytes, and supply a numeric confidence level (0–100) for the labels to be returned. An example below shows how to convert an uploaded file into base64-encoded image bytes.

$image = fopen($request->file('photo')->getPathName(), 'r');
$bytes = fread($image, $request->file('photo')->getSize());

Create the Request

Create a request to Rekognition. Supply the image bytes, and enter a minimum confidence level for your labels.

Detect Nudity

$results = $client->detectModerationLabels([
'Image' => ['Bytes' => $bytes],
'MinConfidence' => 50
])['ModerationLabels'];

# Check to see if nudity labels were returned
$containsNudity = array_search('Explicit Nudity', array_column($results, 'Name'));

Detect Text in Photo

$results = $client->detectText([
'Image' => ['Bytes' => $bytes],
'MinConfidence' => 50
])['ModerationLabels'];

# Create single string of all words detected
foreach($results as $item)
{
if($item['Type'] === 'WORD')
{
$string .= $item['DetectedText'] . ' ';
}
}