PHP Integration
Standalone PHP function with file-based cache and a full Laravel middleware class for blocking blacklisted IPs.
3 min setup
PHP 7.4+
Laravel support
Standalone PHP Function
A single function with file-based caching that works with any PHP application:
ipwhois-guard.php
<?php
/**
* Check if an IP is listed on the IPWhois Blacklist.
* Returns threat data array if blocked, null if clean.
* Uses file-based cache (1 hour TTL).
*/
function ipwhois_check(string $ip, int $min_confidence = 70): ?array {
$cache_dir = sys_get_temp_dir() . '/ipwhois_cache';
if (!is_dir($cache_dir)) {
@mkdir($cache_dir, 0755, true);
}
$cache_file = $cache_dir . '/' . md5($ip) . '.json';
// Check cache (1 hour TTL)
if (file_exists($cache_file) && (time() - filemtime($cache_file)) < 3600) {
$cached = json_decode(file_get_contents($cache_file), true);
if ($cached && !empty($cached['listed']) && ($cached['confidence'] ?? 0) >= $min_confidence) {
return $cached;
}
return null;
}
// Query the API
$ctx = stream_context_create([
'http' => ['timeout' => 3, 'ignore_errors' => true]
]);
$json = @file_get_contents(
'https://bl.ipwhois.net/api/check?ip=' . urlencode($ip),
false,
$ctx
);
if ($json === false) {
return null; // Fail open
}
$data = json_decode($json, true);
@file_put_contents($cache_file, $json);
if (!empty($data['listed']) && ($data['confidence'] ?? 0) >= $min_confidence) {
return $data;
}
return null;
}
/**
* Report a malicious IP to the blacklist.
*/
function ipwhois_report(string $ip, string $type = 'brute-force', string $message = ''): bool {
$ch = curl_init('https://bl.ipwhois.net/api/report');
curl_setopt_array($ch, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query([
'ip' => $ip,
'type' => $type,
'message' => $message
]),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
]);
$resp = curl_exec($ch);
$ok = curl_getinfo($ch, CURLINFO_HTTP_CODE) === 200;
curl_close($ch);
return $ok;
}
Usage
require_once 'ipwhois-guard.php';
$ip = $_SERVER['REMOTE_ADDR'];
$threat = ipwhois_check($ip);
if ($threat) {
http_response_code(403);
die('Access denied. Threat: ' . ($threat['threat_type'] ?? 'unknown'));
}
Laravel Middleware
app/Http/Middleware/IPWhoisGuard.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
class IPWhoisGuard
{
public function handle(Request $request, Closure $next)
{
$ip = $request->ip();
$data = Cache::remember("ipwhois_bl_{$ip}", 3600, function () use ($ip) {
try {
$response = Http::timeout(3)->get('https://bl.ipwhois.net/api/check', [
'ip' => $ip,
]);
return $response->json();
} catch (\Exception $e) {
return ['listed' => false]; // Fail open
}
});
if (!empty($data['listed']) && ($data['confidence'] ?? 0) >= 70) {
abort(403, 'Access denied: IP is blacklisted.');
}
return $next($request);
}
}
Register in app/Http/Kernel.php (Laravel 10) or bootstrap/app.php (Laravel 11+):
Laravel 10 - app/Http/Kernel.php
protected $routeMiddleware = [
// ...
'ipwhois' => \App\Http\Middleware\IPWhoisGuard::class,
];
Laravel 11+ - bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
$middleware->alias([
'ipwhois' => \App\Http\Middleware\IPWhoisGuard::class,
]);
})
Apply to routes:
Route::middleware('ipwhois')->group(function () {
Route::post('/login', [AuthController::class, 'login']);
Route::resource('/admin', AdminController::class);
});
Testing
# Test standalone function
php -r "
require 'ipwhois-guard.php';
var_dump(ipwhois_check('8.8.8.8'));
// Should output: NULL (clean IP)
"
# Test Laravel route
php artisan serve &
curl -s http://localhost:8000/login -X POST
Troubleshooting
- allow_url_fopen disabled: The standalone function uses
file_get_contents. If disabled in php.ini, switch to curl: replace thefile_get_contentscall withcurl_exec. - Cache directory not writable: Ensure PHP can write to
/tmp/ipwhois_cache/. On shared hosting, use a directory within your document root. - Laravel Http facade timeout: The default timeout is 30 seconds. The code sets it to 3 seconds. If you still see slow responses, check your server's DNS resolution.
- Behind load balancer: Configure Laravel's trusted proxies in
app/Http/Middleware/TrustProxies.phpso$request->ip()returns the real client IP.
IPWhois Blacklist — Community-driven IP threat intelligence — ipwhois.net