PHP code example of aubes / csp-bundle

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

    

aubes / csp-bundle example snippets


use Aubes\CSPBundle\Attribute\CSPGroup;
use Aubes\CSPBundle\Attribute\CSPDisabled;

// Apply a specific group
#[CSPGroup('admin')]
class AdminController extends AbstractController
{
    // All actions use the "admin" CSP group
}

// Apply one enforcing + one report-only group
#[CSPGroup('default')]
#[CSPGroup('strict_ro')]
class DashboardController extends AbstractController {}

// Override at method level
class PageController extends AbstractController
{
    #[CSPGroup('strict')]
    public function secure(): Response {}
}

// Disable CSP entirely
#[CSPDisabled]
class WebhookController extends AbstractController {}

use Aubes\CSPBundle\CSP;

class ExampleController extends AbstractController
{
    public function __invoke(CSP $csp): Response
    {
        // Add to default group
        $csp->addDirective('script-src', 'https://cdn.example.com');

        // Add to a specific group
        $csp->addDirective('img-src', 'https://images.example.com', 'admin');

        return $this->render('example.html.twig');
    }
}

use Aubes\CSPBundle\Event\CSPViolationEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener]
class CSPViolationListener
{
    public function __invoke(CSPViolationEvent $event): void
    {
        // $event->group  : the CSP group name
        // $event->report : the sanitized report data
    }
}

#[CSPGroup('default')]
#[CSPGroup('strict')]
class MyController extends AbstractController {}
shell
php bin/console csp:check