PHP code example of joshghent / loginllama

1. Go to this page and download the library: Download joshghent/loginllama library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

joshghent / loginllama example snippets



LoginLlama\LoginLlama;

$loginllama = new LoginLlama('your-api-key');

// IP and User-Agent are automatically detected from $_SERVER!
$result = $loginllama->check($_POST['email']);

if ($result['status'] === 'error' || $result['risk_score'] > 5) {
    error_log('Suspicious login blocked: ' . implode(', ', $result['codes']));
    http_response_code(403);
    echo json_encode(['error' => 'Login blocked']);
    exit;
}

// Continue with login...
echo json_encode(['success' => true]);

$result = $loginllama->check(
    $_POST['email'],
    ['request' => $request]
);

$result = $loginllama->check('[email protected]', [
    'ipAddress' => '203.0.113.42',
    'userAgent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)...'
]);



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use LoginLlama\LoginLlama;

class AuthController extends Controller
{
    private LoginLlama $loginllama;

    public function __construct()
    {
        $this->loginllama = new LoginLlama(env('LOGINLLAMA_API_KEY'));
    }

    public function login(Request $request)
    {
        $email = $request->input('email');

        // Pass Laravel request explicitly for auto-detection
        $result = $this->loginllama->check($email, [
            'request' => $request,
            'geoCountry' => 'US',
            'geoCity' => 'San Francisco'
        ]);

        if ($result['risk_score'] > 5) {
            return response()->json([
                'error' => 'Suspicious login'
            ], 403);
        }

        return response()->json(['success' => true]);
    }
}



namespace App\Controller;

use LoginLlama\LoginLlama;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;

class AuthController extends AbstractController
{
    private LoginLlama $loginllama;

    public function __construct()
    {
        $this->loginllama = new LoginLlama($_ENV['LOGINLLAMA_API_KEY']);
    }

    #[Route('/login', methods: ['POST'])]
    public function login(Request $request): JsonResponse
    {
        $email = $request->request->get('email');

        // Pass Symfony request explicitly for auto-detection
        $result = $this->loginllama->check($email, [
            'request' => $request
        ]);

        if ($result['risk_score'] > 5) {
            return $this->json([
                'error' => 'Suspicious login'
            ], 403);
        }

        return $this->json(['success' => true]);
    }
}


// In your theme's functions.php or a custom plugin

add_action('wp_login', function($user_login, $user) {
    gent are auto-detected from $_SERVER
        $result = $loginllama->check($user_login);

        if ($result['risk_score'] > 5) {
            // Log suspicious login
            error_log("Suspicious login for user: {$user_login}, risk: {$result['risk_score']}");

            // Optionally block the login
            wp_logout();
            wp_die('Login blocked due to suspicious activity');
        }
    } catch (Exception $e) {
        error_log('LoginLlama error: ' . $e->getMessage());
        // Fail open - allow login to proceed
    }
}, 10, 2);

use LoginLlama\LoginLlama;

$loginllama = new LoginLlama('your-api-key');

[
    'status' => 'success' | 'error',
    'message' => 'string',
    'codes' => ['VALID'] | ['IP_ADDRESS_SUSPICIOUS', ...],
    'risk_score' => 0-10, // integer
    'environment' => 'production' | 'staging',
    'meta' => [...] // optional
]

// Auto-detect from $_SERVER
$result = $loginllama->check('[email protected]');

// Pass request explicitly (Laravel/Symfony)
$result = $loginllama->check('[email protected]', [
    'request' => $request
]);

// Manual override
$result = $loginllama->check('[email protected]', [
    'ipAddress' => '203.0.113.42',
    'userAgent' => 'Mozilla/5.0...'
]);

// With additional context
$result = $loginllama->check('[email protected]', [
    'emailAddress' => '[email protected]',
    'geoCountry' => 'US',
    'geoCity' => 'San Francisco'
]);



namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use LoginLlama\LoginLlama;

class LoginLlamaMiddleware
{
    private LoginLlama $loginllama;

    public function __construct()
    {
        $this->loginllama = new LoginLlama(env('LOGINLLAMA_API_KEY'));
    }

    public function handle(Request $request, Closure $next)
    {
        $middleware = $this->loginllama->middleware();
        $middleware($request);
        return $next($request);
    }
}



namespace App\EventSubscriber;

use LoginLlama\LoginLlama;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class LoginLlamaSubscriber implements EventSubscriberInterface
{
    private LoginLlama $loginllama;

    public function __construct()
    {
        $this->loginllama = new LoginLlama($_ENV['LOGINLLAMA_API_KEY']);
    }

    public function onKernelRequest(RequestEvent $event): void
    {
        $middleware = $this->loginllama->middleware();
        $middleware($event->getRequest());
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::REQUEST => 'onKernelRequest',
        ];
    }
}

use LoginLlama\LoginLlama;

$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_X_LOGINLLAMA_SIGNATURE'] ?? '';
$secret = getenv('WEBHOOK_SECRET');

if (!LoginLlama::verifyWebhookSignature($payload, $signature, $secret)) {
    http_response_code(401);
    exit('Invalid signature');
}

$event = json_decode($payload, true);
// Handle event...
http_response_code(200);

use LoginLlama\LoginCheckStatus;

// Example status codes:
LoginCheckStatus::VALID
LoginCheckStatus::IP_ADDRESS_SUSPICIOUS
LoginCheckStatus::KNOWN_BOT
LoginCheckStatus::GEO_IMPOSSIBLE_TRAVEL
LoginCheckStatus::USER_AGENT_SUSPICIOUS
// ... and more

use LoginLlama\LoginLlama;

$loginllama = new LoginLlama('your-api-key');

try {
    $result = $loginllama->check('[email protected]');
} catch (\Exception $e) {
    if (str_contains($e->getMessage(), 'IP address could not be detected')) {
        // No IP available - pass ipAddress or request explicitly
    }
    error_log('LoginLlama error: ' . $e->getMessage());
}

try {
    $result = $loginllama->check($email);

    if ($result['risk_score'] > 5) {
        // Block suspicious login
        http_response_code(403);
        echo json_encode(['error' => 'Login blocked']);
        exit;
    }
} catch (\Exception $e) {
    error_log('LoginLlama error: ' . $e->getMessage());
    // Fail open - allow login to proceed
}

$loginllama = new LoginLlama(getenv('LOGINLLAMA_API_KEY'));