PHP code example of easyshield / php-secure-headers

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

    

easyshield / php-secure-headers example snippets



// Create the headers instance
$headers = new \EasyShield\SecureHeaders\SecureHeaders();
$headers->enableAllSecurityHeaders();

// Apply headers
foreach ($headers->getHeaders() as $name => $value) {
    header("$name: $value");
}


// app/Http/Middleware/SecureHeadersMiddleware.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use EasyShield\SecureHeaders\SecureHeaders;
use Symfony\Component\HttpFoundation\Response;

class SecureHeadersMiddleware
{
    private SecureHeaders $headers;
    
    public function __construct()
    {
        $this->headers = new SecureHeaders();
        $this->headers->enableAllSecurityHeaders();
    }
    
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        
        foreach ($this->headers->getHeaders() as $name => $value) {
            $response->headers->set($name, $value);
        }
        
        return $response;
    }
}

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\App\Http\Middleware\SecureHeadersMiddleware::class);
})


// src/EventSubscriber/SecureHeadersSubscriber.php
namespace App\EventSubscriber;

use EasyShield\SecureHeaders\SecureHeaders;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class SecureHeadersSubscriber implements EventSubscriberInterface
{
    private SecureHeaders $headers;
    
    public function __construct()
    {
        $this->headers = new SecureHeaders();
        $this->headers->enableAllSecurityHeaders();
    }
    
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::RESPONSE => 'onKernelResponse',
        ];
    }
    
    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }
        
        $response = $event->getResponse();
        
        foreach ($this->headers->getHeaders() as $name => $value) {
            $response->headers->set($name, $value);
        }
    }
}

$headers = new \EasyShield\SecureHeaders\SecureHeaders();

// Enable only specific headers
$headers->enableHSTS()
        ->enableXFrameOptions()
        ->enableXContentTypeOptions();

$headers->enableCSP([
    'default-src' => ["'self'"],
    'script-src' => ["'self'", "https://trusted.com"],
    'style-src' => ["'self'", "'unsafe-inline'"],
    'img-src' => ["'self'", "data:", "https:"],
    'font-src' => ["'self'", "https://fonts.gstatic.com"],
    'connect-src' => ["'self'", "https://api.example.com"]
]);

// Get CSP builder instance and configure it
$headers->csp()
    ->allowScripts('https://trusted.com')
    ->allowStyles('https://fonts.googleapis.com')
    ->allowImages('https://images.example.com', 'data:')
    ->allowFonts('https://fonts.gstatic.com')
    ->allowConnections('https://api.example.com')
    ->blockFrames()
    ->useStrictDynamic()
    ->upgradeInsecureRequests();

// Apply the CSP configuration
$headers->enableCSP();

// Analyze HTML and automatically add sources to CSP
$html = '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
$headers->csp()->detectExternalResourcesFromHtml($html);
$headers->enableCSP();

// Inject nonces into script and style tags
$html = '<script>console.log("Hello");</script>';
$modifiedHtml = $headers->csp()->injectNoncesToHtml($html);
$headers->enableCSP();

// Output: <script nonce="random-nonce-value">console.log("Hello");</script>

$headers->csp()
    ->addScriptHash('sha256', 'HashOfYourInlineScript')
    ->addStyleHash('sha256', 'HashOfYourInlineStyle');
$headers->enableCSP();

$headers->enableHSTS(
    maxAge: 31536000, // 1 year
    

$headers->enablePermissionsPolicy([
    'camera' => ["'self'"],
    'microphone' => ["'none'"],
    'geolocation' => ["'self'", "https://maps.example.com"]
]);

$headers->enableClientHintsPolicy([
    'ch-ua-platform' => '*',
    'ch-ua-mobile' => 'true',
    'ch-ua' => 'self'
]);

$headers->enableCriticalCH([
    'Sec-CH-UA-Platform',
    'Sec-CH-UA-Mobile',
    'Sec-CH-UA'
]);


// ایجاد نمونه هدر
$headers = new \EasyShield\SecureHeaders\SecureHeaders();
$headers->enableAllSecurityHeaders();

// اعمال هدرها
foreach ($headers->getHeaders() as $name => $value) {
    header("$name: $value");
}


// app/Http/Middleware/SecureHeadersMiddleware.php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use EasyShield\SecureHeaders\SecureHeaders;
use Symfony\Component\HttpFoundation\Response;

class SecureHeadersMiddleware
{
    private SecureHeaders $headers;
    
    public function __construct()
    {
        $this->headers = new SecureHeaders();
        $this->headers->enableAllSecurityHeaders();
    }
    
    public function handle(Request $request, Closure $next): Response
    {
        $response = $next($request);
        
        foreach ($this->headers->getHeaders() as $name => $value) {
            $response->headers->set($name, $value);
        }
        
        return $response;
    }
}

->withMiddleware(function (Middleware $middleware) {
    $middleware->append(\App\Http\Middleware\SecureHeadersMiddleware::class);
})


// src/EventSubscriber/SecureHeadersSubscriber.php
namespace App\EventSubscriber;

use EasyShield\SecureHeaders\SecureHeaders;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;

class SecureHeadersSubscriber implements EventSubscriberInterface
{
    private SecureHeaders $headers;
    
    public function __construct()
    {
        $this->headers = new SecureHeaders();
        $this->headers->enableAllSecurityHeaders();
    }
    
    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::RESPONSE => 'onKernelResponse',
        ];
    }
    
    public function onKernelResponse(ResponseEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }
        
        $response = $event->getResponse();
        
        foreach ($this->headers->getHeaders() as $name => $value) {
            $response->headers->set($name, $value);
        }
    }
}

$headers = new \EasyShield\SecureHeaders\SecureHeaders();

// فعال‌سازی فقط هدرهای خاص
$headers->enableHSTS()
        ->enableXFrameOptions()
        ->enableXContentTypeOptions();

$headers->enableCSP([
    'default-src' => ["'self'"],
    'script-src' => ["'self'", "https://trusted.com"],
    'style-src' => ["'self'", "'unsafe-inline'"],
    'img-src' => ["'self'", "data:", "https:"],
    'font-src' => ["'self'", "https://fonts.gstatic.com"],
    'connect-src' => ["'self'", "https://api.example.com"]
]);

// دریافت نمونه CSP builder و پیکربندی آن
$headers->csp()
    ->allowScripts('https://trusted.com')
    ->allowStyles('https://fonts.googleapis.com')
    ->allowImages('https://images.example.com', 'data:')
    ->allowFonts('https://fonts.gstatic.com')
    ->allowConnections('https://api.example.com')
    ->blockFrames()
    ->useStrictDynamic()
    ->upgradeInsecureRequests();

// اعمال پیکربندی CSP
$headers->enableCSP();

// تحلیل HTML و افزودن خودکار منابع به CSP
$html = '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
$headers->csp()->detectExternalResourcesFromHtml($html);
$headers->enableCSP();

// تزریق nonce به تگ‌های script و style
$html = '<script>console.log("Hello");</script>';
$modifiedHtml = $headers->csp()->injectNoncesToHtml($html);
$headers->enableCSP();

// خروجی: <script nonce="مقدار-تصادفی-nonce">console.log("Hello");</script>

$headers->csp()
    ->addScriptHash('sha256', 'HashOfYourInlineScript')
    ->addStyleHash('sha256', 'HashOfYourInlineStyle');
$headers->enableCSP();

$headers->enableHSTS(
    maxAge: 31536000, // 1 year
    

$headers->enablePermissionsPolicy([
    'camera' => ["'self'"],
    'microphone' => ["'none'"],
    'geolocation' => ["'self'", "https://maps.example.com"]
]);
bash
composer 
bash
composer