Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Mixed Content Scanner Laravel Package

spatie/mixed-content-scanner

Scan a website for mixed content by crawling pages and flagging insecure http:// resources in common HTML tags (img, script, iframe, link, etc.). Use MixedContentScanner with a logger to report where mixed content is found or missing.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/mixed-content-scanner
    

    Add to composer.json if using a monorepo or custom package.

  2. First Use Case: Scan a URL for mixed content (HTTP resources on HTTPS pages) via CLI or programmatically:

    use Spatie\MixedContentScanner\MixedContentScanner;
    use Spatie\MixedContentScanner\MixedContentLogger;
    
    $logger = new class implements MixedContentLogger {
        public function logMixedContentFound(string $url, string $mixedContentUrl) {
            echo "Mixed content found at {$url}: {$mixedContentUrl}\n";
        }
        public function logNoMixedContentFound(string $url) {
            echo "No mixed content found at {$url}\n";
        }
    };
    
    $scanner = new MixedContentScanner($logger);
    $scanner->scan('https://your-laravel-app.test');
    
  3. Key Files:

    • MixedContentScanner.php: Core logic.
    • MixedContentLogger.php: Interface for logging results.
    • src/: Source directory for all classes.

CLI Alternative

For quick scans, use the companion CLI package:

composer require spatie/mixed-content-scanner-cli
./vendor/bin/mixed-content-scanner scan https://your-laravel-app.test

Implementation Patterns

Workflows

  1. Pre-Deployment Scans: Integrate into Laravel’s app/Console/Kernel.php to run scans before deployments:

    protected function schedule(Schedule $schedule) {
        $schedule->command(MixedContentScannerCommand::class)
                ->everyFiveMinutes()
                ->when(function () {
                    return app()->environment('production');
                });
    }
    
  2. Custom Logging: Extend MixedContentLogger to integrate with Laravel’s logging:

    use Illuminate\Support\Facades\Log;
    
    $logger = new class implements MixedContentLogger {
        public function logMixedContentFound(string $url, string $mixedContentUrl) {
            Log::warning("Mixed content at {$url}: {$mixedContentUrl}");
        }
        public function logNoMixedContentFound(string $url) {
            Log::info("No mixed content at {$url}");
        }
    };
    
  3. Batch Scanning: Scan multiple URLs (e.g., from a database):

    $urls = Url::where('is_production', true)->pluck('url');
    foreach ($urls as $url) {
        $scanner->scan($url);
    }
    
  4. Artisan Command: Create a custom command for manual triggering:

    php artisan make:command ScanMixedContent
    
    // app/Console/Commands/ScanMixedContent.php
    public function handle() {
        $scanner = new MixedContentScanner(new MixedContentLogger());
        $scanner->scan($this->argument('url'));
    }
    

    Usage:

    php artisan scan:mixed-content https://your-site.com
    

Integration Tips

  • Laravel Queues: Wrap scans in a job for async processing:
    use Illuminate\Bus\Queueable;
    use Spatie\MixedContentScanner\Jobs\ScanMixedContent;
    
    ScanMixedContent::dispatch('https://your-site.com')->onQueue('scans');
    
  • Laravel Horizon: Monitor scan jobs in real-time.
  • Laravel Notifications: Send alerts for mixed content via email/Slack:
    $logger = new class implements MixedContentLogger {
        public function logMixedContentFound(string $url, string $mixedContentUrl) {
            Notification::route('mail', 'admin@example.com')
                        ->notify(new MixedContentAlert($url, $mixedContentUrl));
        }
    };
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting:

    • Scanning large sites may hit rate limits. Use --delay in CLI or add delays in code:
      $scanner->setDelayBetweenRequests(2); // 2-second delay
      
    • For aggressive scanning, implement exponential backoff.
  2. False Positives:

    • Some resources (e.g., CDN-hosted assets) may appear as mixed content but are safe. Whitelist them:
      $scanner->ignoreUrls([
          'https://cdn.example.com/*',
          'https://fonts.googleapis.com/*'
      ]);
      
  3. Self-Signed Certificates:

    • The scanner uses PHP’s file_get_contents under the hood, which may fail on self-signed certs. Disable SSL verification only for testing:
      $scanner->setDisableSslVerification(true); // Avoid in production!
      
  4. JavaScript/Iframe Content:

    • The scanner may miss dynamically loaded content (e.g., via JS). Combine with tools like Lighthouse for comprehensive checks.
  5. Redirects:

    • Mixed content may appear after redirects. Ensure the scanner follows redirects:
      $scanner->setFollowRedirects(true); // Default is true
      

Debugging

  • Verbose Output: Enable debug mode for detailed logs:
    $scanner->setDebug(true);
    
  • Check Headers: Use curl -v or browser dev tools to verify mixed content manually if the scanner misses issues.

Extension Points

  1. Custom Scanners: Extend MixedContentScanner to add logic (e.g., scan only specific paths):

    class CustomScanner extends MixedContentScanner {
        public function scanOnly(string $url, string $path) {
            $fullUrl = rtrim($url, '/') . '/' . ltrim($path, '/');
            return $this->scan($fullUrl);
        }
    }
    
  2. Database Storage: Store scan results in a table for historical analysis:

    // After scanning, save to DB
    MixedContentResult::create([
        'url' => $url,
        'has_mixed_content' => $scanner->hasMixedContent(),
        'scanned_at' => now(),
    ]);
    
  3. Parallel Scanning: Use Laravel’s parallel helper or pest/phpunit parallel tests to scan multiple URLs concurrently:

    parallel([
        fn() => $scanner->scan('https://site1.com'),
        fn() => $scanner->scan('https://site2.com'),
    ]);
    
  4. CI/CD Integration: Fail builds on mixed content detection (e.g., GitHub Actions):

    # .github/workflows/scan.yml
    - name: Scan for mixed content
      run: |
        ./vendor/bin/mixed-content-scanner scan https://your-site.com
        if [ $? -ne 0 ]; then exit 1; fi
    

Config Quirks

  • Default User Agent: The scanner uses MixedContentScanner as the user agent. Override for better mimicry:
    $scanner->setUserAgent('Mozilla/5.0 (compatible; Laravel Scanner/1.0)');
    
  • Timeouts: Adjust timeout for slow responses:
    $scanner->setTimeout(30); // 30 seconds
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport