<tutorialjinni.com/>

Virustotal API File Scanning PHP Example

Posted Under: API, PHP, Programming, Security on Feb 12, 2016
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.

$VTAPIKEY="YOUR_API_KEY";
$hash=md5("PATH_TO_FILE");
$apiEndPoint="https://www.virustotal.com/vtapi/v2/file/report?";
$finalURL=$apiEndPoint."resource=$hash&apikey=".$VTAPIKEY;

$json=file_get_contents($finalURL);
$j=json_decode($json);
if($j->response_code==1){
	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.
$VTAPIKEY="YOUR_API_KEY";
$apiEndPoint="http://www.virustotal.com/vtapi/v2/file/scan";

$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);
if($j->response_code==1){
    $md5=$j->md5;
    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"; }
© Tutorial Jinni