Google SafeBrowsing v4 PHP Example

Posted on December 1, 2016 at 2:08 pm

Sample PHP function to check Google SafeBrowsing v4 API:

function Lookup_GoogleSafeBrowsing_v4($url)
{
    $data = '{
      "client": {
        "clientId": "TestClient",
        "clientVersion": "1.0"
      },
      "threatInfo": {
        "threatTypes":      ["MALWARE", "SOCIAL_ENGINEERING"],
        "platformTypes":    ["LINUX"],
        "threatEntryTypes": ["URL"],
        "threatEntries": [
          {"url": "'.$url.'"}
        ]
      }
    }';
 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://safebrowsing.googleapis.com/v4/threatMatches:find?key=ENTER_YOUR_API_KEY_HERE");
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json", 'Content-Length: ' . strlen($data)));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $response = (array) json_decode(curl_exec($ch), true);
    curl_close ($ch);
    return ($response['matches'][0]['threatType']) ? true : false;
}

*** Change the ENTER_YOUR_API_KEY_HERE string with your API key ***

You can test it like this:

echo "Host gumblar.cn is:<br />";
echo Lookup_GoogleSafeBrowsing_v4("gumblar.cn")?"Malware":"Clean";

More information here:

https://developers.google.com/safe-browsing/v4/get-started

Usage is limited to 10,000 requests /24 hours per API key:

https://developers.google.com/safe-browsing/v4/usage-limits

Other Posts

Updated Posts