Image moderation

Updated at:

Use AI Guardrails SDK for PHP to scan images for risky content — including pornography, terrorism, ads, QR codes, undesirable scenes, and logos — with either synchronous or asynchronous detection.

This SDK accepts image URLs only. Local files and binary data are not supported. URLs must be HTTP or HTTPS and no longer than 2,048 characters.

Prerequisites

Before you begin, make sure you have:

  • Installed PHP dependencies using the required PHP version. Using a different version causes operation calls to fail. See Install PHP dependencies.

  • An Alibaba Cloud RAM user with AccessKey ID and AccessKey secret stored as environment variables:

    • ALIBABA_CLOUD_ACCESS_KEY_ID

    • ALIBABA_CLOUD_ACCESS_KEY_SECRET

Synchronous image scan (recommended)

ImageSyncScanRequest sends a synchronous moderation request and returns real-time results. Use this when your application needs an immediate decision — for example, blocking uploads before they are stored.

For full parameter details, see Synchronous detection.

Supported regions: cn-shanghai, cn-beijing, cn-shenzhen, ap-southeast-1

<?php

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Green\Green;

try {
    // Reuse this client instance across requests to avoid repeated connections.
    AlibabaCloud::accessKeyClient(
        getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
        ->timeout(10)           // Request timeout: 10 seconds
        ->connectTimeout(3)     // Connection timeout: 3 seconds (if value < 1, unit is automatically converted to milliseconds)
        ->regionId('cn-shanghai')
        ->asDefaultClient();

    // One task per image. For batch scans, add more task arrays.
    // Batch processing time is determined by the slowest image;
    // larger batches have a higher chance of extended response times.
    $task1 = [
        'dataId' => '<your-business-data-id>',
        'url'    => '<url-of-image-to-scan>',
    ];

    $response = Green::v20180509()->imageSyncScan()
        ->timeout(10)
        ->connectTimeout(3)
        ->body(json_encode([
            'tasks'   => [$task1],
            'scenes'  => ['porn'],          // Add scenes as needed: porn, terrorism, ad, qrcode, logo
            'bizType' => '<your-biz-type>', // Optional: your business scenario identifier
        ]))
        ->request();

    if (200 === $response->code) {
        foreach ($response->data as $taskResult) {
            if (200 === $taskResult->code) {
                foreach ($taskResult->results as $sceneResult) {
                    // scene: the moderation category (e.g., "porn")
                    // suggestion: the recommended action — "pass", "review", or "block"
                    echo $sceneResult->scene . ': ' . $sceneResult->suggestion . PHP_EOL;
                }
            } else {
                print_r("task process fail:" . $response->code);
            }
        }
    } else {
        echo 'Request failed. Code: ' . $response->code . PHP_EOL;
    }
} catch (Exception $e) {
    echo $e->getMessage() . PHP_EOL;
}
Optical character recognition (OCR) billing for card and certificate images is based on the number of images scanned multiplied by the unit price per card or certificate type.

Submit asynchronous image moderation tasks

ImageAsyncScanRequest submits a moderation task and returns immediately without waiting for results. Retrieve results by polling with ImageAsyncScanResultsRequest or by configuring a callback notification.

Use asynchronous moderation when processing large volumes of images or when real-time results are not required.

For full parameter details, see /green/image/asyncscan and /green/image/results.

Supported regions: cn-shanghai, cn-beijing, cn-shenzhen, ap-southeast-1

<?php

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Green\Green;

try {
    AlibabaCloud::accessKeyClient(
        getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
        ->timeout(10)
        ->connectTimeout(3)     // Connection timeout: 3 seconds (if value < 1, unit is automatically converted to milliseconds)
        ->regionId('cn-shanghai')
        ->asDefaultClient();

    $task1 = [
        'dataId' => '<your-business-data-id>',
        'url'    => '<url-of-image-to-scan>',
    ];

    $result = Green::v20180509()->imageAsyncScan()
        ->timeout(10)
        ->connectTimeout(3)
        ->body(json_encode([
            'tasks'   => [$task1],
            'scenes'  => ['porn', 'terrorism'],
            'bizType' => '<your-biz-type>',
        ]))
        ->request();

    print_r($result->toArray());
} catch (ClientException $e) {
    echo $e->getMessage() . PHP_EOL;
} catch (ServerException $e) {
    echo $e->getMessage() . PHP_EOL;
    echo $e->getErrorCode() . PHP_EOL;
    echo $e->getRequestId() . PHP_EOL;
    echo $e->getErrorMessage() . PHP_EOL;
}

Query asynchronous moderation results

ImageAsyncScanResultsRequest retrieves the results of one or more previously submitted asynchronous tasks.

Supported regions: cn-shanghai, cn-beijing, cn-shenzhen, ap-southeast-1

<?php

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Green\Green;

try {
    AlibabaCloud::accessKeyClient(
        getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
        ->timeout(10)
        ->connectTimeout(3)     // Connection timeout: 3 seconds (if value < 1, unit is automatically converted to milliseconds)
        ->regionId('cn-shanghai')
        ->asDefaultClient();

    $result = Green::v20180509()->imageAsyncScanResults()
        ->timeout(10)
        ->connectTimeout(3)
        ->body(json_encode(['<task-id-1>', '<task-id-2>'])) // IDs from the async scan response
        ->request();

    print_r($result->toArray());
} catch (ClientException $e) {
    echo $e->getMessage() . PHP_EOL;
} catch (ServerException $e) {
    echo $e->getMessage() . PHP_EOL;
    echo $e->getErrorCode() . PHP_EOL;
    echo $e->getRequestId() . PHP_EOL;
    echo $e->getErrorMessage() . PHP_EOL;
}

Submit feedback on moderation results

If a moderation result is incorrect, use ImageScanFeedbackRequest to correct it. AI Guardrails adds the image to a blocklist or allowlist based on your feedback. When a similar image is submitted later, AI Guardrails returns results based on the label you provided.

For background on how feedback affects future results, see Detection result feedback.

Supported regions: cn-shanghai, cn-beijing, cn-shenzhen, ap-southeast-1

<?php

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Green\Green;

try {
    AlibabaCloud::accessKeyClient(
        getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')
    )
        ->timeout(10)
        ->connectTimeout(3)     // Connection timeout: 3 seconds (if value < 1, unit is automatically converted to milliseconds)
        ->regionId('cn-shanghai')
        ->asDefaultClient();

    $result = Green::v20180509()->imageScanFeedback()
        ->timeout(10)
        ->connectTimeout(3)
        ->body(json_encode([
            'url'        => '<url-of-image-to-correct>',
            'suggestion' => 'block',            // Your corrected label: "pass" or "block"
            'scenes'     => ['porn', 'terrorism'],
        ]))
        ->request();

    print_r($result->toArray());
} catch (ClientException $e) {
    echo $e->getMessage() . PHP_EOL;
} catch (ServerException $e) {
    echo $e->getMessage() . PHP_EOL;
    echo $e->getErrorCode() . PHP_EOL;
    echo $e->getRequestId() . PHP_EOL;
    echo $e->getErrorMessage() . PHP_EOL;
}

What's next