PHP code example of zappzarapp / security

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

    

zappzarapp / security example snippets


use Zappzarapp\Security\Headers\Builder\SecurityHeadersBuilder;

$headers = SecurityHeadersBuilder::recommended()->build();
foreach ($headers as $name => $value) {
    header("{$name}: {$value}");
}

use Zappzarapp\Security\Csp\HeaderBuilder;
use Zappzarapp\Security\Csp\Directive\CspDirectives;
use Zappzarapp\Security\Csp\Nonce\NonceGenerator;

$generator = new NonceGenerator();
$csp = HeaderBuilder::build(CspDirectives::strict(), $generator);
header("Content-Security-Policy: {$csp}");

$nonce = $generator->get();
echo "<script nonce=\"{$nonce}\">console.log('Safe!');</script>";

use Zappzarapp\Security\Csrf\CsrfProtection;
use Zappzarapp\Security\Csrf\Storage\SessionCsrfStorage;

$csrf = new CsrfProtection(new SessionCsrfStorage());

// Generate token for form
$token = $csrf->generateToken();
echo '<input type="hidden" name="_token" value="' . $token->value() . '">';

// Validate on submission
if (!$csrf->validateToken($_POST['_token'])) {
    throw new Exception('CSRF validation failed');
}

use Zappzarapp\Security\Sanitization\Html\HtmlSanitizer;
use Zappzarapp\Security\Sanitization\Path\PathValidator;

// Sanitize HTML (removes dangerous tags/attributes)
$sanitizer = new HtmlSanitizer();
$safe = $sanitizer->sanitize($userInput);

// Validate file paths (prevent directory traversal)
$validator = new PathValidator('/var/www/uploads');
if (!$validator->isValid($userPath)) {
    throw new Exception('Invalid path');
}