Virustotal API File Scanning PHP Example

Posted Under: API, cURL, PHP, Programming, Security on Feb 12, 2016
Virustotal API File Scanning PHP Example
This tutorial focuses on integration virustotal.com API in a PHP application without using any other API wrapper. This make the integration more integrated, reliable as you have complete control and visibility, efficient and fast as there no bloat code in it. The tutorial aims to provide a file scanning functionality to files uploaded to the server. Small website usually do not have the resources to host or the money to purchase a professional grade antivirus solution and keep it updated. This post is for them. It is also in conjunction to another post Secure File Upload in PHP

First thing you need is the API key. You get it by making account on the virustotal.com and generate a public key. Public key is for virustotal public API which we are going to use.

First approach is instant, you just take the hash of the uploaded file and send it virustotal to check if it is malicious or not.


	echo "Success Found Hash
"; if($j->positives>0){ echo "File is Malicious with a score of $j->positives/$j->total"; }else{ echo "File is Clean!"; } } if($j->response_code==0){ echo "File or its analysis is not available on Virustotal"; }
Second approach is a little slow and it is recommended that it should be done in a batch mode because it may take many minutes to complete. This approach is used after first approach. In this we upload a file to Virustotal and wait for the results.

$post['apikey'] = $VTAPIKEY;
$post['file'] = '@'.realpath("PATH_TO_FILE");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$apiEndPoint);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$json = curl_exec ($ch);
$j=  json_decode($json);
    echo "File Queued Wating for Results 
"; echo "The MD5 hash of the file is $md5"; //Wait for 2 Minutes and check againg //with the first approach describe above //using the MD5 hash. }else{ echo "Something went wrong. Receive Error: $j->verbose_msg"; }