How to Scan a File for Viruses & Malware in PHP

Cloudmersive
2 min readMar 8, 2024

--

Client-side file upload is a common vector for passive virus and malware attacks. With a flexible, low-code antivirus solution, we can implement a layer of security against potentially malicious files stored in sensitive server locations.

Using the below ready-to-run PHP code, we can take advantage of a free API to help us scan uploaded files for viruses and malware. This API will send copies of files from our server to a powerful antivirus sandbox for an in-memory scan. This scan offers predictive threat detection capabilities and also references a threat signature database containing more than 17 million virus & malware signatures.

We can structure our API call in a few quick steps.

First, let’s install the PHP client (using Composer) by executing the following command from the command line:

composer require cloudmersive/cloudmersive_virusscan_api_client

Next, let’s use the below code examples to call the function:

<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');



$apiInstance = new Swagger\Client\Api\ScanApi(


new GuzzleHttp\Client(),
$config
);
$input_file = "/path/to/inputfile"; // \SplFileObject | Input file to perform the operation on.

try {
$result = $apiInstance->scanFile($input_file);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling ScanApi->scanFile: ', $e->getMessage(), PHP_EOL;
}
?>

To authorize our API call, we’ll need a free API key, which will allow a limit of 800 API calls per month (with no additional commitments). We can use file paths from our server to scan files, and we can use the “CleanResult” Boolean response to determine outcomes for infected files.

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet