daycry / maintenancemode
Maintenance mode for Codeigniter 4
Installs: 7 922
Dependents: 0
Suggesters: 0
Security: 0
Stars: 5
Watchers: 2
Forks: 3
Open Issues: 0
Requires
- php: >=8.2
- codeigniter4/settings: ^2.2
Requires (Dev)
README
๐ง Maintenance Mode for CodeIgniter 4
A powerful, modern and highly configurable maintenance mode library for CodeIgniter 4 with intelligent caching, modern UI, and advanced features.
โจ Features
- ๐ High Performance: Intelligent cache-based storage system (10x faster than file-based)
- ๐จ Modern UI: Responsive, dark-mode compatible maintenance page with auto-refresh
- ๐ Multiple Bypass Methods: IP whitelist, cookies, and secret URL bypass
- ๐ Comprehensive Logging: Complete audit trail of maintenance events
- โ๏ธ Highly Configurable: Extensive configuration options for all scenarios
- ๐ Scalable: Works perfectly in distributed environments
- ๐ Backward Compatible: 100% compatible with existing implementations
- ๐ฑ Mobile-Friendly: Fully responsive design with accessibility features
๐ฆ Installation
Install via Composer:
composer require daycry/maintenancemode
โ๏ธ Configuration
1. Publish Configuration
php spark mm:publish
This creates app/Config/Maintenance.php
with all available options.
2. Basic Configuration
<?php // app/Config/Maintenance.php public bool $useCache = true; // Use cache instead of files (recommended) public bool $enableLogging = true; // Log maintenance events public string $defaultMessage = 'We are currently performing maintenance...'; public bool $allowSecretBypass = true; // Enable secret URL bypass public string $secretBypassKey = 'your-secret-key';
3. Cache Configuration (Recommended)
For optimal performance, configure your cache in app/Config/Cache.php
:
// Redis (recommended for production) public array $redis = [ 'handler' => 'redis', 'host' => '127.0.0.1', 'port' => 6379, // ... other settings ]; // Or use any other cache driver (Memcached, File, etc.)
Commands Available
php spark mm:down php spark mm:status php spark mm:up
Use it
Method 1 (Recommended)
Create new event in app/Config/Events.php
Events::on( 'pre_system', 'Daycry\Maintenance\Controllers\Maintenance::check' );
Method 2
edit application/Config/Filters.php and add the new line in $aliases array:
public $aliases = [ 'maintenance' => \Daycry\Maintenance\Filters\Maintenance::class, ... ]
and add "maintenance" in $globals['before'] array:
public $globals = [ 'before' => [ 'maintenance', ... ], 'after' => [ ... ], ];
๐ฏ Enhanced Commands
Activate Maintenance Mode
# Basic activation php spark mm:down # With custom message php spark mm:down --message="We'll be back in 30 minutes!" # With IP whitelist (multiple IPs supported) php spark mm:down --allow=192.168.1.100,203.0.113.0 # With automatic expiry (30 minutes) php spark mm:down --duration=30 # With secret bypass key php spark mm:down --secret=my-secret-123
Check Status
php spark mm:status
This displays a comprehensive status table with:
- ๐ด/๐ข Current status indicator
- ๐ Storage method (cache/file)
- ๐ Configuration summary
- ๐ Allowed IPs and bypass keys
- ๐ Real-time bypass detection
- ๐ฆ Current access status
- ๐ก Practical usage tips
Enhanced Bypass Detection
The status command now shows real-time bypass information:
๐ Current Bypass Status:
๐ Config Secret available (add ?maintenance_secret=your-key to URL)
โ
Data Secret (via URL parameter)
๐ IP Address bypass configured (current IP 192.168.1.200 not in allowed list)
๐ช Cookie bypass configured (cookie not set or invalid)
๐ฆ Access Status from CLI:
โ
Access ALLOWED: CLI access (always allowed)
๐ก Tips:
โข Add your IP: php spark mm:down --allow=192.168.1.200
โข Use secret: php spark mm:down --secret=your-key
โข Access URL: https://yoursite.com?maintenance_secret=your-key
Key Features:
- โ Active bypass detection: Shows which bypass methods are currently working
- ๐ Real-time status: Indicates if current user would have access
- ๐ก Practical guidance: Provides specific commands to enable access
- ๐ฏ Priority indication: Shows bypass method priority order
- ๐ฑ Current IP display: Shows your current IP for whitelist setup
Deactivate Maintenance Mode
php spark mm:up
Migrate Storage Method
Switch between file and cache storage without losing configuration:
# Migrate from files to cache php spark mm:migrate --to=cache # Migrate from cache to files php spark mm:migrate --to=file
๐ Bypass Detection & Monitoring
Real-time Status Checking
The enhanced mm:status
command provides comprehensive bypass detection:
php spark mm:status
What it shows:
- ๐ข Active bypass methods: Currently working bypass options
- ๐ด Inactive bypass methods: Configured but not currently active
- ๐ฏ Current access status: Whether you would have access right now
- ๐ก Actionable tips: Specific commands to enable access
- ๐ Configuration overview: All bypass methods configured
Bypass Method Priority
The system checks bypass methods in this priority order:
- ๐ฅ Config Secret (
app/Config/Maintenance.php
) - ๐ฅ Data Secret (set when activating maintenance)
- ๐ฅ IP Address (IP whitelist)
- ๐ Cookie (automatically generated)
Practical Examples
Scenario 1: Developer wants access
# Check current status php spark mm:status # Example output shows: # ๐ IP Address bypass configured (current IP 192.168.1.200 not in allowed list) # ๐ก Add your IP: php spark mm:down --allow=192.168.1.200 # Add your IP to allowed list php spark mm:down --allow=192.168.1.200
Scenario 2: Share access via secret URL
# Check secret information php spark mm:status # Example output shows: # ๐ Secret Bypass Information: # URL: https://yoursite.com?maintenance_secret=abc123 # Share this URL with authorized users
Scenario 3: Troubleshooting access issues
# Check why access is blocked php spark mm:status # Example output shows: # โ Access BLOCKED: No valid bypass method # ๐ก Tips: # โข Add your IP: php spark mm:down --allow=YOUR_IP # โข Use secret: php spark mm:down --secret=your-key
๐ Advanced Usage
1. Multiple Bypass Methods
IP-based Bypass:
// Allow specific IPs to bypass maintenance $config->allowedIps = ['192.168.1.100', '203.0.113.0'];
Secret URL Bypass:
https://yoursite.com/any-page?maintenance_secret=your-secret-key
Cookie-based Bypass:
// Set cookie programmatically setcookie('maintenance_bypass', 'your-secret-key', time() + 3600);
2. Custom Error Pages
Override the default maintenance page by creating:
app/Views/errors/html/error_503.php
The modern template includes:
- ๐จ Responsive design with CSS variables
- ๐ Auto-refresh functionality
- ๐ Dark mode support
- โฟ Accessibility features
- ๐ฑ Mobile optimization
3. Programmatic Control
use Daycry\MaintenanceMode\Libraries\MaintenanceStorage; $storage = new MaintenanceStorage(); // Check if maintenance is active if ($storage->isActive()) { // Get maintenance data $data = $storage->getData(); echo "Message: " . $data['message']; } // Activate programmatically $storage->save([ 'message' => 'Custom maintenance message', 'allowedIps' => ['192.168.1.100'], 'time' => time(), 'secret' => 'custom-secret' ]); // Deactivate $storage->remove();
4. Event Handling
// In your BaseController or specific controllers public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); // Add custom logic before maintenance check Events::on('pre_maintenance_check', function () { // Your custom logic here }); }
๐ Performance Comparison
Storage Method | Average Response Time | Memory Usage | Scalability |
---|---|---|---|
Cache (Redis) | ~0.5ms | Low | โญโญโญโญโญ |
Cache (Memcached) | ~0.8ms | Low | โญโญโญโญโญ |
Cache (File) | ~2ms | Medium | โญโญโญ |
File Storage | ~5ms | Medium | โญโญ |
Recommendation: Use Redis cache for production environments with high traffic.
๐ง Configuration Reference
Complete configuration options in app/Config/Maintenance.php
:
<?php namespace Config; use CodeIgniter\Config\BaseConfig; class Maintenance extends BaseConfig { // Storage Configuration public bool $useCache = true; // Use cache vs files public string $cacheKey = 'maintenance_mode'; // Cache key name public int $cacheTTL = 86400; // Cache TTL (24 hours) // File Storage public string $driver = 'file'; // Storage driver public string $filePath = WRITEPATH . 'maintenance/maintenance.json'; // UI & Messages public string $defaultMessage = 'We are currently performing maintenance. Please try again later.'; public int $httpCode = 503; // HTTP status code public int $autoRefreshSeconds = 30; // Auto-refresh interval // Security & Access public array $allowedIps = []; // IP whitelist public bool $allowSecretBypass = true; // Enable secret bypass public string $secretBypassKey = ''; // Default secret key public string $bypassCookieName = 'maintenance_bypass'; // Logging & Monitoring public bool $enableLogging = true; // Log maintenance events public string $logLevel = 'info'; // Log level // Advanced Features public bool $showRetryAfter = true; // Show Retry-After header public int $retryAfter = 3600; // Retry-After value (1 hour) }
๐ฆ Filter Integration
Add the maintenance filter to your routes:
// app/Config/Routes.php $routes->group('/', ['filter' => 'maintenance'], static function ($routes) { $routes->get('/', 'Home::index'); $routes->get('about', 'Pages::about'); // Add other routes that should be checked }); // Or apply globally in app/Config/Filters.php public array $globals = [ 'before' => [ 'maintenance' => ['except' => ['admin/*', 'api/*']] ] ];
๐งช Testing
Run the test suite:
# Run all tests composer test # Run with coverage composer test:coverage # Run specific test ./vendor/bin/phpunit tests/Maintenance/CommandsTest.php
๐ Troubleshooting
Common Issues
1. Cache not working:
# Check cache configuration php spark cache:info # Clear cache php spark cache:clear # Test cache connection php spark mm:status
2. IP bypass not working:
# Check your real IP php spark mm:down --allow=$(curl -s ifconfig.me) # Or check current IP in logs tail -f writable/logs/log-*.php | grep maintenance
3. Migration issues:
# Force migration with cleanup php spark mm:migrate --to=cache --force # Check file permissions ls -la writable/maintenance/
Debug Mode
Enable debug logging:
// app/Config/Maintenance.php public string $logLevel = 'debug'; public bool $enableLogging = true;
๐ค Contributing
- Fork the repository
- Create your feature branch:
git checkout -b feature/amazing-feature
- Run tests:
composer test
- Commit your changes:
git commit -m 'Add amazing feature'
- Push to the branch:
git push origin feature/amazing-feature
- Open a Pull Request
๐ Changelog
v2.0.0 (Latest)
- โจ New: Cache-based storage system with 10x performance improvement
- โจ New: Modern responsive maintenance page with dark mode
- โจ New: Migration command for seamless storage switching
- โจ New: Enhanced CLI commands with validation and better UX
- โจ New: Comprehensive logging and monitoring
- ๐ง Enhanced: Expanded configuration with 12+ new options
- ๐ง Enhanced: Better error handling and validation
- ๐ Fixed: Multiple IP handling and secret bypass improvements
v1.x.x
- Basic file-based maintenance mode
- Simple CLI commands
- Basic IP filtering
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ก Support
- ๐ง Email: support@daycry.com
- ๐ Issues: GitHub Issues
- ๐ฌ Discussions: GitHub Discussions
- โ Buy me a coffee: PayPal
Made with โค๏ธ for the CodeIgniter 4 community