A powerful PHP library for managing security headers in web applications. This library helps you implement best security practices by easily configuring various security headers including Content Security Policy (CSP), HTTP Strict Transport Security (HSTS), and more.
- 🛡️ Easy configuration of security headers
- 🔒 Support for Content Security Policy (CSP)
- 🔐 HTTP Strict Transport Security (HSTS)
- 🚫 X-Frame-Options protection
- 🔍 X-Content-Type-Options
- 🛑 X-XSS-Protection
- 📝 Referrer Policy
- 🎯 Permissions Policy
- 📱 Client Hints Policy
- ⚙️ Two security levels: Basic and Strict
- 🔄 Automatic nonce generation for CSP
- ⚡ Framework integrations (Laravel & Symfony)
You can install the package via composer:
composer require easyshield/php-secure-headers
Just 5 lines of code to enable all security headers:
<?php
// Create the headers instance
$headers = new \EasyShield\SecureHeaders\SecureHeaders();
$headers->enableAllSecurityHeaders();
// Apply headers
foreach ($headers->getHeaders() as $name => $value) {
header("$name: $value");
}
In Laravel, just add the middleware:
<?php
// 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;
}
}
Then register it in bootstrap/app.php
:
->withMiddleware(function (Middleware $middleware) {
$middleware->append(\App\Http\Middleware\SecureHeadersMiddleware::class);
})
<?php
// 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);
}
}
}
Enable only specific headers:
$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();
Auto-detecting external resources from HTML:
// 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();
Auto-injecting nonces into HTML:
// 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>
Using hashes for inline scripts instead of nonces:
$headers->csp()
->addScriptHash('sha256', 'HashOfYourInlineScript')
->addStyleHash('sha256', 'HashOfYourInlineStyle');
$headers->enableCSP();
$headers->enableHSTS(
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true
);
$headers->enablePermissionsPolicy([
'camera' => ["'self'"],
'microphone' => ["'none'"],
'geolocation' => ["'self'", "https://maps.example.com"]
]);
For detailed Laravel instructions, see examples/Laravel/README.md.
Note: When using the Laravel integration, please include the following attribution in your project's README:
Laravel integration based on PHP Secure Headers by Shadi Ghorbani.
For detailed Symfony instructions, see examples/Symfony/README.md.
Note: When using the Symfony integration, please include the following attribution in your project's README:
Symfony integration based on PHP Secure Headers by Shadi Ghorbani.
$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'
]);
The library supports two security levels:
- Allows 'unsafe-inline' for styles
- Less restrictive CSP
- Basic permissions policy
- No 'unsafe-inline'
- Strict CSP with nonce
- Comprehensive permissions policy
- Enforces upgrade-insecure-requests
For more examples, please refer to the comprehensive guide.
composer test
# Run all checks (style, syntax, static analysis, tests)
composer check-all
# Fix code style
composer fix-style
# Generate test coverage report
composer test-coverage
Your feedback is highly appreciated! If you have any suggestions, ideas, or comments, please:
- Open an issue on GitHub
- Share how you're using the library
- Suggest improvements or new features
See CONTRIBUTING.md for more information on how to contribute.
If you discover any security related issues, please email shadighorbani7171@gmail.com instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
یک کتابخانه قدرتمند PHP برای مدیریت هدرهای امنیتی در برنامههای وب. این کتابخانه با پیکربندی آسان انواع هدرهای امنیتی از جمله Content Security Policy (CSP)، HTTP Strict Transport Security (HSTS) و موارد دیگر، به شما کمک میکند بهترین روشهای امنیتی را پیادهسازی کنید.
- 🛡️ پیکربندی آسان هدرهای امنیتی
- 🔒 پشتیبانی از سیاست امنیتی محتوا (CSP)
- 🔐 امنیت انتقال سختگیرانه HTTP (HSTS)
- 🚫 محافظت X-Frame-Options
- 🔍 X-Content-Type-Options
- 🛑 X-XSS-Protection
- 📝 سیاست ارجاع (Referrer Policy)
- 🎯 سیاست مجوزها (Permissions Policy)
- 📱 سیاست اطلاعات مشتری (Client Hints Policy)
- ⚙️ دو سطح امنیتی: پایه و سختگیرانه
- 🔄 تولید خودکار nonce برای CSP
- ⚡ ادغام با فریمورکها (Laravel و Symfony)
میتوانید این پکیج را از طریق Composer نصب کنید:
composer require easyshield/php-secure-headers
تنها با 5 خط کد، تمام هدرهای امنیتی را فعال کنید:
<?php
// ایجاد نمونه هدر
$headers = new \EasyShield\SecureHeaders\SecureHeaders();
$headers->enableAllSecurityHeaders();
// اعمال هدرها
foreach ($headers->getHeaders() as $name => $value) {
header("$name: $value");
}
در Laravel، کافی است میدلور را اضافه کنید:
<?php
// 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;
}
}
سپس آن را در bootstrap/app.php
ثبت کنید:
->withMiddleware(function (Middleware $middleware) {
$middleware->append(\App\Http\Middleware\SecureHeadersMiddleware::class);
})
<?php
// 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:
// تحلیل HTML و افزودن خودکار منابع به CSP
$html = '<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>';
$headers->csp()->detectExternalResourcesFromHtml($html);
$headers->enableCSP();
تزریق خودکار nonce به HTML:
// تزریق nonce به تگهای script و style
$html = '<script>console.log("Hello");</script>';
$modifiedHtml = $headers->csp()->injectNoncesToHtml($html);
$headers->enableCSP();
// خروجی: <script nonce="مقدار-تصادفی-nonce">console.log("Hello");</script>
استفاده از hash برای اسکریپتهای درونخطی به جای nonce:
$headers->csp()
->addScriptHash('sha256', 'HashOfYourInlineScript')
->addStyleHash('sha256', 'HashOfYourInlineStyle');
$headers->enableCSP();
$headers->enableHSTS(
maxAge: 31536000, // 1 year
includeSubDomains: true,
preload: true
);
$headers->enablePermissionsPolicy([
'camera' => ["'self'"],
'microphone' => ["'none'"],
'geolocation' => ["'self'", "https://maps.example.com"]
]);
برای مثالهای بیشتر و راهنمای کامل، لطفاً به راهنمای جامع مراجعه کنید.
نظرات شما بسیار ارزشمند است! اگر پیشنهاد، ایده یا نظری دارید، لطفاً:
- در GitHub یک issue باز کنید
- نحوه استفاده خود از کتابخانه را به اشتراک بگذارید
- بهبودها یا ویژگیهای جدید را پیشنهاد دهید
برای اطلاعات بیشتر در مورد نحوه مشارکت، به CONTRIBUTING.md مراجعه کنید.
اگر مشکلات مرتبط با امنیت پیدا کردید، لطفاً به جای استفاده از issue tracker، به آدرس shadighorbani7171@gmail.com ایمیل بزنید.
مجوز MIT (MIT). لطفاً برای اطلاعات بیشتر به فایل مجوز مراجعه کنید.