PHP code example of shammaa / laravel-security

1. Go to this page and download the library: Download shammaa/laravel-security 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/ */

    

shammaa / laravel-security example snippets


// Laravel 11+
->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\Shammaa\LaravelSecurity\Http\Middleware\SecurityMiddleware::class);
});

// Or Laravel 10
protected $middlewareGroups = [
    'web' => [
        \Shammaa\LaravelSecurity\Http\Middleware\SecurityMiddleware::class,
    ],
];

// Sanitize any input
$clean = security_sanitize($request->input('name'));

// Filter XSS
$safe = security_xss_filter($html);

// Rate Limiting
if (!security_rate_limit('api:' . $userId)) {
    return response()->json(['error' => 'Too many requests'], 429);
}

use Shammaa\LaravelSecurity\Facades\Security;

// Sanitize
$clean = Security::sanitize($input);

// Filter XSS
$safe = Security::xssFilter($html);

// Validate file
if (Security::validateFile($file)) {
    $path = Security::storeFile($file);
}

// Check password strength
$result = Security::checkPassword($password);
if (!$result['valid']) {
    // $result['errors'] contains the errors
}

// Check if account is locked
if (Security::isLocked($email)) {
    return back()->withErrors(['email' => 'Account locked']);
}

// Record failed login attempt
Security::recordFailedLogin($email);

// Clear failed attempts on success
Security::clearFailedLogins($email);

return [
    // Enable/disable protection
    'sql_injection' => [
        'enabled' => true,  // true = enabled, false = disabled
        'block_on_detect' => true,  // Auto-block on detection
    ],
    
    'xss' => [
        'enabled' => true,
        'filter_input' => true,  // Filter inputs
    ],
    
    // Or use .env
    // SECURITY_SQL_INJECTION_ENABLED=true
    // SECURITY_XSS_ENABLED=true
];

'input' =&gt; [
    'whitelist_routes' =&gt; ['admin/*', 'dashboard/posts/*'],
    'whitelist_parameters' =&gt; ['content', 'description', 'body', 'html'],
],

'xss' =&gt; [
    'whitelist_routes' =&gt; ['admin/*', 'dashboard/*'],
],

'headers' =&gt; [
    'whitelist_routes' =&gt; ['admin/*', 'dashboard/*'],
],

'excluded_routes' => ['api/ai/*', 'api/webhooks/*', 'api/external/*'],

// .env
SECURITY_EXCLUDED_ROUTES=api/ai/*

// Now your AI routes won't be blocked
Route::post('/api/ai/rewrite', [AIController::class, 'rewrite']);
Route::post('/api/ai/generate', [AIController::class, 'generate']);

// In Controller
public function upload(Request $request)
{
    $file = $request->file('document');
    
    // Simple way - Helper Function
    if (!security_validate_file($file)) {
        return back()->withErrors(['file' => 'File not allowed']);
    }
    
    // Secure storage
    $path = security_store_file($file);
    
    // Or use Facade
    if (Security::validateFile($file)) {
        $path = Security::storeFile($file);
    }
    
    return response()->json(['path' => $path]);
}

// In Controller or Middleware
public function apiEndpoint(Request $request)
{
    $userId = auth()->id();
    
    // Rate limit: 100 requests per minute
    if (!Security::rateLimit("api:{$userId}", 100, 1)) {
        return response()->json([
            'error' => 'Too many requests'
        ], 429);
    }
    
    // Rest of the code...
}

// In LoginController
public function login(Request $request)
{
    $email = $request->email;
    
    // Simple way - Helper Functions
    if (security_is_locked($email)) {
        return back()->withErrors(['email' => 'Account locked. Try again later.']);
    }
    
    if (!Auth::attempt($request->only('email', 'password'))) {
        // Record failed attempt
        security_record_failed_login($email);
        return back()->withErrors(['email' => 'Invalid credentials']);
    }
    
    // Success - clear failed attempts
    security_clear_failed_logins($email);
    
    return redirect('/dashboard');
    
    // Or use Facade
    // if (Security::isLocked($email)) { ... }
    // Security::recordFailedLogin($email);
    // Security::clearFailedLogins($email);
}

// Sanitize any input
$name = security_sanitize($request->input('name'));
$email = security_sanitize($request->input('email'));

// Or use Facade
$name = Security::sanitize($request->input('name'));

// In Blade
{!! Security::xssFilter($user->bio) !!}

// Or Helper
{!! security_xss_filter($user->bio) !!}

use Shammaa\LaravelSecurity\Events\SecurityThreatDetected;

Event::listen(SecurityThreatDetected::class, function ($event) {
    // Send email, notification, etc...
    Mail::to('[email protected]')->send(new SecurityAlert($event));
});
bash
php artisan security:scan
php artisan security:scan --fix  # Attempt to fix issues
bash
php artisan security:report
php artisan security:report --days=60 --format=table
bash
php artisan security:unblock 192.168.1.1
bash
php artisan security:clean --days=30
php artisan security:clean --days=30 --force  # Without confirmation