easyshield/php-secure-headers
Composer 安装命令:
composer require easyshield/php-secure-headers
包简介
A simple yet powerful PHP library for managing security headers in web applications
README 文档
README
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.
Features
- 🛡️ 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)
Installation
You can install the package via composer:
composer require easyshield/php-secure-headers
Quick Usage
Method 1: Plain PHP
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"); }
Method 2: Laravel Integration
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); })
Method 3: Symfony Integration
<?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); } } }
Custom Configuration
Enable only specific headers:
$headers = new \EasyShield\SecureHeaders\SecureHeaders(); // Enable only specific headers $headers->enableHSTS() ->enableXFrameOptions() ->enableXContentTypeOptions();
Custom CSP
Method 1: Using Array Configuration
$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"] ]);
Method 2: Using CSP Builder (Fluent API)
// 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();
Advanced CSP Features
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();
Custom HSTS
$headers->enableHSTS( maxAge: 31536000, // 1 year includeSubDomains: true, preload: true );
Custom Permissions Policy
$headers->enablePermissionsPolicy([ 'camera' => ["'self'"], 'microphone' => ["'none'"], 'geolocation' => ["'self'", "https://maps.example.com"] ]);
Framework Integration
Laravel
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.
Symfony 7/8
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.
Advanced Usage
Client Hints Policy
$headers->enableClientHintsPolicy([ 'ch-ua-platform' => '*', 'ch-ua-mobile' => 'true', 'ch-ua' => 'self' ]);
Critical Client Hints
$headers->enableCriticalCH([ 'Sec-CH-UA-Platform', 'Sec-CH-UA-Mobile', 'Sec-CH-UA' ]);
Security Levels
The library supports two security levels:
Basic Level
- Allows 'unsafe-inline' for styles
- Less restrictive CSP
- Basic permissions policy
Strict Level (Default)
- No 'unsafe-inline'
- Strict CSP with nonce
- Comprehensive permissions policy
- Enforces upgrade-insecure-requests
More Examples
For more examples, please refer to the comprehensive guide.
Testing
composer test
Code Quality
# Run all checks (style, syntax, static analysis, tests) composer check-all # Fix code style composer fix-style # Generate test coverage report composer test-coverage
Feedback and Contributions
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.
Security
If you discover any security related issues, please email shadighorbani7171@gmail.com instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.
هدرهای امنیتی PHP
یک کتابخانه قدرتمند 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
استفاده سریع
روش 1: PHP ساده
تنها با 5 خط کد، تمام هدرهای امنیتی را فعال کنید:
<?php // ایجاد نمونه هدر $headers = new \EasyShield\SecureHeaders\SecureHeaders(); $headers->enableAllSecurityHeaders(); // اعمال هدرها foreach ($headers->getHeaders() as $name => $value) { header("$name: $value"); }
روش 2: ادغام با Laravel
در 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); })
روش 3: ادغام با Symfony
<?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();
CSP سفارشی
روش 1: استفاده از پیکربندی آرایهای
$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"] ]);
روش 2: استفاده از CSP Builder (API روان)
// دریافت نمونه 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();
ویژگیهای پیشرفته CSP
تشخیص خودکار منابع خارجی از 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();
HSTS سفارشی
$headers->enableHSTS( maxAge: 31536000, // 1 year includeSubDomains: true, preload: true );
Custom Permissions Policy
$headers->enablePermissionsPolicy([ 'camera' => ["'self'"], 'microphone' => ["'none'"], 'geolocation' => ["'self'", "https://maps.example.com"] ]);
مستندات بیشتر
برای مثالهای بیشتر و راهنمای کامل، لطفاً به راهنمای جامع مراجعه کنید.
مشارکت
نظرات شما بسیار ارزشمند است! اگر پیشنهاد، ایده یا نظری دارید، لطفاً:
- در GitHub یک issue باز کنید
- نحوه استفاده خود از کتابخانه را به اشتراک بگذارید
- بهبودها یا ویژگیهای جدید را پیشنهاد دهید
برای اطلاعات بیشتر در مورد نحوه مشارکت، به CONTRIBUTING.md مراجعه کنید.
امنیت
اگر مشکلات مرتبط با امنیت پیدا کردید، لطفاً به جای استفاده از issue tracker، به آدرس shadighorbani7171@gmail.com ایمیل بزنید.
مجوز
مجوز MIT (MIT). لطفاً برای اطلاعات بیشتر به فایل مجوز مراجعه کنید.
easyshield/php-secure-headers 适用场景与选型建议
easyshield/php-secure-headers 是一款 基于 HTML 开发的 Composer 扩展包,目前已累计 12 次下载、GitHub Stars 达 20, 最近一次更新时间为 2025 年 03 月 25 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「security」 「headers」 「csp」 「X-Frame-Options」 「hsts」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 easyshield/php-secure-headers 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 easyshield/php-secure-headers 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 easyshield/php-secure-headers 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Permissions-Policy (Feature-Policy) header builder and middleware for Laravel
Provide a way to secure accesses to all routes of an symfony application.
PHP polyfill for the Apache Functions. The aim is to provides functions as the PHP way in order to get them available even if PHP is not running as an Apache module.
Helper bundle, configure the request headers from a given base URL.
It's a barebone security class written on PHP
Sets default security configurations
统计信息
- 总下载量: 12
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 20
- 点击次数: 36
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-03-25