PHP code example of attachmentav / virus-scan-sdk

1. Go to this page and download the library: Download attachmentav/virus-scan-sdk library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

attachmentav / virus-scan-sdk example snippets


use AttachmentAV\AttachmentAVApi;
use AttachmentAV\Configuration;
use AttachmentAV\Region;

$api = new AttachmentAVApi(Configuration::saas('<API_KEY_PLACEHOLDER>', Region::EU));

$result = $api->scanSyncFile('/path/to/file');

if ($result->isInfected()) {
    echo 'Malware detected: ' . $result->getFinding();
}

$result->getStatus();       // 'clean', 'infected', or 'no' (file could not be scanned)
$result->getFinding();      // e.g. 'EICAR-AV-Test' for infected files, otherwise null
$result->getSize();         // 8100
$result->getRealFileType(); // 'ASCII text / 8-bit Unicode Transformation Format'

use AttachmentAV\AttachmentAVApi;
use AttachmentAV\Configuration;
use AttachmentAV\Region;

$api = new AttachmentAVApi(Configuration::saas('<API_KEY_PLACEHOLDER>', Region::US));

use AttachmentAV\AttachmentAVApi;
use AttachmentAV\Configuration;

$api = new AttachmentAVApi(Configuration::selfHosted('<API_KEY_PLACEHOLDER>', 'https://attachmentav.yourcompany.com/api/v1'));

use AttachmentAV\AttachmentAVApi;
use AttachmentAV\Configuration;

$config = Configuration::saas('<API_KEY_PLACEHOLDER>')
    ->withMaxRetries(5)              // retries when requests are throttled (429), default: 3, 0 disables retries
    ->withRetryDelayMs(1000)         // base delay of the exponential backoff, default: 500 ms
    ->withTimeout(90)                // request timeout in seconds, default: 65 (sync scans take up to 60 seconds)
    ->withDefaultHeaders(['X-Request-Id' => 'abc']);

$api = new AttachmentAVApi($config);

$httpClient = new \GuzzleHttp\Client(['timeout' => 65, 'connect_timeout' => 10, 'proxy' => 'http://proxy:3128']);

$api = new AttachmentAVApi($config, $httpClient);

$config = Configuration::fromArray([
    'deployment' => 'self-hosted',   // or 'saas'
    'api_key' => getenv('ATTACHMENTAV_API_KEY'),
    'region' => 'eu',                // SaaS only
    'base_url' => getenv('ATTACHMENTAV_BASE_URL'), // 

$result = $api->scanSyncFile('/path/to/file');

// Or pass the content as a string, a stream resource, or a PSR-7 stream.
$result = $api->scanSyncBinary(file_get_contents('/path/to/file'));
$result = $api->scanSyncBinary(fopen('/path/to/file', 'rb'));

$result = $api->scanSyncDownload('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf');

// Optional: headers to send when downloading the file
$result = $api->scanSyncDownload('https://example.com/private.pdf', ['Authorization' => 'Bearer ...']);

$result = $api->scanSyncS3('<BUCKET_NAME_PLACEHOLDER>', '<OBJECT_KEY_PLACEHOLDER>');

// For versioned buckets
$result = $api->scanSyncS3('<BUCKET_NAME_PLACEHOLDER>', '<OBJECT_KEY_PLACEHOLDER>', '<OBJECT_VERSION_PLACEHOLDER>');

$api->scanAsyncDownload(
    'https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf',
    callbackUrl: 'https://api.yourcompany.com/attachmentav/callback',
    customData: json_encode(['documentId' => 42]) // optional, passed through to the callback (max. 16 KB)
);

$traceId = bin2hex(random_bytes(16));
$pollingUrl = $api->scanAsyncDownload('https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf', traceId: $traceId);
// $pollingUrl: https://eu.developer.attachmentav.com/v1/scan/async/result?trace_id=... (null when a callback URL is used)

do {
    sleep(10);
    $result = $api->getAsyncResult($traceId);
} while ($result === null);

$api->scanAsyncS3(
    '<BUCKET_NAME_PLACEHOLDER>',
    '<OBJECT_KEY_PLACEHOLDER>',
    callbackUrl: 'https://api.yourcompany.com/attachmentav/callback'
);

// Or with polling
$api->scanAsyncS3('<BUCKET_NAME_PLACEHOLDER>', '<OBJECT_KEY_PLACEHOLDER>', traceId: $traceId);

$cursor = null;
do {
    $page = $api->getCallbackFailures('https://api.yourcompany.com/attachmentav/callback', $cursor);
    foreach ($page as $failure) {
        echo $failure->getTime()?->format(DATE_ATOM) . ' ' . $failure->getDownloadUrl() . ' ' . $failure->getErrorJson() . PHP_EOL;
    }
    $cursor = $page->getNextCursor();
} while ($cursor !== null);

$usage = $api->getUsage();
echo $usage->getCredits() . ' of ' . $usage->getQuotaLimit() . ' credits left';

$tenantId = $api->whoami()->getTenantId();

$api->test(); // throws AuthenticationException if the API key is invalid

use AttachmentAV\Callback\CallbackVerifier;
use AttachmentAV\Region;

$verifier = CallbackVerifier::forRegion(Region::EU, '<TENANT_ID_PLACEHOLDER>');

$payload = $verifier->verifyAndParse(
    file_get_contents('php://input'),   // the raw request body
    $_SERVER['HTTP_X_SIGNATURE'] ?? null,
    $_SERVER['HTTP_X_TIMESTAMP'] ?? null,
    'https://api.yourcompany.com/attachmentav/callback' // the callback URL used when submitting the scan job
); // throws InvalidSignatureException if the signature is invalid or older than 5 minutes

$payload->getStatus();     // 'clean', 'infected', or 'no'
$payload->getTraceId();
$payload->getCustomData();

use AttachmentAV\Exception\ExceptionInterface;
use AttachmentAV\Exception\RateLimitException;

try {
    $result = $api->scanSyncFile($path);
} catch (RateLimitException $e) {
    // quota exceeded or still throttled after retries
} catch (ExceptionInterface $e) {
    // any other error
}

use AttachmentAV\Laravel\Rules\VirusFree;

$request->validate([
    'attachment' => ['

use AttachmentAV\AttachmentAVApi;
use AttachmentAV\Laravel\Facades\AttachmentAV;

$result = AttachmentAV::scanSyncFile($request->file('attachment')->getRealPath());

class DocumentController
{
    public function store(Request $request, AttachmentAVApi $attachmentAV) { /* ... */ }
}

use AttachmentAV\Callback\CallbackVerifier;
use Illuminate\Http\Request;

Route::post('/attachmentav/callback', function (Request $request, CallbackVerifier $verifier) {
    if (!$verifier->verify($request->getContent(), $request->header('X-Signature'), $request->header('X-Timestamp'), url('/attachmentav/callback'))) {
        abort(403);
    }
    $payload = \AttachmentAV\Model\CallbackPayload::fromJson($request->getContent());
    // ...
    return response()->noContent();
});

use AttachmentAV\AttachmentAVApi;
use Symfony\Component\HttpFoundation\File\UploadedFile;

final class UploadController
{
    public function __construct(private AttachmentAVApi $attachmentAV) {}

    public function upload(UploadedFile $file): void
    {
        $result = $this->attachmentAV->scanSyncFile($file->getPathname());
        // ...
    }
}

$api = new AttachmentAVApi($config, $psr18Client, $psr17RequestFactory, $psr17StreamFactory);
bash
php artisan vendor:publish --tag=attachmentav-config