PHP code example of prahsys / laravel-perimeter

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

    

prahsys / laravel-perimeter example snippets


// routes/web.php or routes/api.php
Route::middleware(['perimeter.protect'])->group(function () {
    Route::post('/upload', [UploadController::class, 'store']);
});

use Prahsys\Perimeter\Facades\Perimeter;

public function upload(Request $request)
{
    $file = $request->file('document');
    
    $scan = Perimeter::scan($file);
    if ($scan->hasThreat()) {
        return response()->json([
            'error' => 'Security threat detected: ' . $scan->getThreat()
        ], 422);
    }
    
    // Process safe file...
}

protected function schedule(Schedule $schedule)
{
    // Daily comprehensive security audit
    $schedule->command('perimeter:audit')->daily();
    
    // Weekly vulnerability scan with specific focus
    $schedule->command('perimeter:report --type=vulnerability')->weekly();
    
    // Weekly security health verification
    $schedule->command('perimeter:health')->weekly();
}

// Register custom event handlers
use Prahsys\Perimeter\Facades\Perimeter;
use App\Notifications\SecurityAlertNotification;

// In your service provider
Perimeter::onThreatDetected(function ($securityEvent) {
    // Notify security team via Slack
    Notification::route('slack', config('security.slack_webhook'))
        ->notify(new SecurityAlertNotification($securityEvent));
    
    // Log to specialized security log
    Log::channel('security')->critical('Security threat detected', [
        'event' => $securityEvent->toArray()
    ]);
});

'artifacts' => [
    'disk' => env('PERIMETER_ARTIFACTS_DISK', 'local'),
    'root_path' => env('PERIMETER_ARTIFACTS_ROOT_PATH', 'perimeter/audits'),
    'retention_days' => env('PERIMETER_ARTIFACTS_RETENTION', 90),
],

// Local storage (default)
'disk' => 'local'

// AWS S3 for distributed environments
'disk' => 's3'

// Custom disk for shared storage
'disk' => 'audit_storage'

// config/filesystems.php
'audit_storage' => [
    'driver' => 's3',
    'key' => env('AWS_ACCESS_KEY_ID'),
    'secret' => env('AWS_SECRET_ACCESS_KEY'),
    'region' => env('AWS_DEFAULT_REGION'),
    'bucket' => env('AWS_BUCKET'),
    'root' => 'security-audits/' . env('SERVER_ID', gethostname()),
],

// In a service provider
Config::set('perimeter.artifacts.root_path', 
    'perimeter/audits/' . env('CLUSTER_NODE_ID', gethostname())
);

use Illuminate\Support\Facades\Storage;

// List available audit dates
$auditDates = Storage::disk(config('perimeter.artifacts.disk'))
    ->directories(config('perimeter.artifacts.root_path'));

// Get artifacts for a specific date
$todayArtifacts = Storage::disk(config('perimeter.artifacts.disk'))
    ->files(config('perimeter.artifacts.root_path') . '/' . now()->format('Y-m-d'));

// Download an artifact file
$artifactContent = Storage::disk(config('perimeter.artifacts.disk'))
    ->get('perimeter/audits/2025-06-26/2025-06-26_14-30-15_abc123def.zip');

// Configure security alerts in config/logging.php:
'channels' => [
    // Send critical security alerts to Slack
    'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'username' => 'Laravel Perimeter',
        'emoji' => ':shield:',
        'level' => 'critical', // Only critical and above go to Slack
    ],
    
    // Dedicated security log for compliance
    'security' => [
        'driver' => 'daily',
        'path' => storage_path('logs/security.log'),
        'level' => 'info', // Capture all security events
        'days' => 90, // Retain logs for compliance purposes
    ],
    
    // Specialized channel for malware detections
    'malware' => [
        'driver' => 'daily',
        'path' => storage_path('logs/malware.log'),
        'level' => 'notice',
    ],
]

// In your AppServiceProvider or dedicated SecurityServiceProvider
use Prahsys\Perimeter\Facades\Perimeter;

public function boot()
{
    // Handle malware detections
    Perimeter::onThreatDetected(function ($securityEvent) {
        // Notify security team
        SecurityTeam::notifyMalwareDetection($securityEvent);
        
        // Quarantine the file
        Storage::move(
            $securityEvent->location, 
            "quarantine/{$securityEvent->details['hash']}"
        );
    });
    
    // Handle vulnerability detections
    Perimeter::onVulnerabilityFound(function ($vulnerability) {
        // Create ticket in issue tracker
        Jira::createSecurityTicket([
            'title' => "Security vulnerability: {$vulnerability->description}",
            'severity' => $vulnerability->severity,
            'details' => $vulnerability->details,
        ]);
    });
    
    // Handle behavioral anomalies
    Perimeter::onAnomalyDetected(function ($anomaly) {
        // Log IP address for further investigation
        if (isset($anomaly->details['source_ip'])) {
            SuspiciousActivity::record($anomaly->details['source_ip']);
        }
    });
}

use Prahsys\Perimeter\Facades\Perimeter;

// Get raw security data with flexible filters
$events = Perimeter::report()
    ->from(now()->subMonth())
    ->to(now())
    ->severity(['critical', 'high'])
    ->type(['malware', 'vulnerability'])
    ->get();

// Generate formatted reports for auditors
$report = Perimeter::report()
    ->from($auditPeriodStart)
    ->to($auditPeriodEnd)
    ->format('csv')
    ->export();

// Generate JSON for API consumption
return Perimeter::report()
    ->from(request('start_date'))
    ->to(request('end_date'))
    ->type(request('event_types', []))
    ->format('json')
    ->get();

use Prahsys\Perimeter\Data\SecurityEventData;

// Create from malware scan results
$eventData = SecurityEventData::fromMalwareScan([
    'timestamp' => now(),
    'severity' => 'critical',
    'threat' => 'malware-signature',
    'file' => '/path/to/file.php',
    'hash' => 'sha256:1234...',
]);

// Create from behavioral analysis
$eventData = SecurityEventData::fromBehavioralAnalysis([
    'rule' => 'privilege_escalation',
    'priority' => 'critical',
    'description' => 'Suspicious activity detected',
    'process' => 'php',
    'user' => 'www-data',
]);

// Create from vulnerability scan
$eventData = SecurityEventData::fromVulnerabilityScan([
    'package' => 'vulnerable/package',
    'version' => '1.2.3',
    'cve' => 'CVE-2025-1234',
    'severity' => 'high',
    'description' => 'Remote code execution vulnerability',
]);
bash
php artisan vendor:publish --tag=perimeter-config
bash
# Complete installation (nstall

# Individual component installation is also available
php artisan perimeter:install-clamav    # Malware protection
php artisan perimeter:install-falco     # Runtime monitoring
php artisan perimeter:install-trivy     # Vulnerability scanning
php artisan perimeter:install-fail2ban  # Intrusion prevention
php artisan perimeter:install-ufw       # Firewall management
bash
# Enable malware monitoring
php artisan perimeter:monitor --services=clamav
bash
# Run audit on all enabled services
php artisan perimeter:audit

# Run audit only on specific services
php artisan perimeter:audit --services=clamav,trivy
php artisan perimeter:audit --services=ufw

# Combine with other options
php artisan perimeter:audit --services=clamav,falco --format=json
bash
php artisan perimeter:health
bash
# Point-in-time check of recent security events
php artisan perimeter:monitor

# Continuous monitoring
php artisan perimeter:monitor

# Service-specific monitoring
php artisan perimeter:monitor --services=falco
bash
# Terminate running monitoring processes (for deployment scripts)
php artisan perimeter:terminate

# Terminate with custom wait time for graceful shutdown
php artisan perimeter:terminate --wait=10
bash
php artisan perimeter:report
bash
php artisan perimeter:health