Weave 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

Files Cdn Laravel Package

baks-dev/files-cdn

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require baks-dev/files-cdn
    

    Ensure your server meets PHP 8.4+ requirements.

  2. Directory Setup

    mkdir -p public/upload && chown -R unit:unit public/upload
    

    Configure the public/upload directory as the upload root.

  3. Security Configuration Generate a hashed password:

    php bin/console security:hash-password
    

    Update config/packages/security.php with your UUIDv7 user and hashed password.

  4. Environment Configuration Add to your .env:

    CDN_HOST=cdn.example.host
    CDN_USER=<your-uuidv7-user>
    CDN_PASS=<plaintext-password>
    
  5. First Use Case Upload a file via HTTP Basic Auth to https://cdn.example.host/cdn/upload. Example using Laravel HTTP client:

    $response = Http::withHeaders([
        'Authorization' => 'Basic ' . base64_encode("{$env('CDN_USER')}:{$env('CDN_PASS')}")
    ])->attach('file', fopen('path/to/file.jpg', 'r'))
      ->post("https://{$env('CDN_HOST')}/cdn/upload");
    

Implementation Patterns

Workflows

  1. File Upload Workflow

    • Laravel Integration: Use middleware to validate/authenticate uploads before forwarding to CDN.
      // app/Http/Middleware/ValidateCdnUpload.php
      public function handle(Request $request, Closure $next) {
          if ($request->isMethod('post') && $request->hasFile('file')) {
              $response = Http::withHeaders([
                  'Authorization' => 'Basic ' . base64_encode("{$env('CDN_USER')}:{$env('CDN_PASS')}")
              ])->attach('file', $request->file('file'))
                ->post("https://{$env('CDN_HOST')}/cdn/upload");
      
              return response()->json($response->json());
          }
          return $next($request);
      }
      
    • Register middleware in app/Http/Kernel.php:
      protected $routeMiddleware = [
          'cdn.upload' => \App\Http\Middleware\ValidateCdnUpload::class,
      ];
      
  2. URL Generation Dynamically generate CDN URLs for uploaded files:

    public function getCdnUrl(string $filename): string {
        return "https://{$this->cdnHost}/uploads/{$filename}";
    }
    
  3. Batch Processing Use Laravel queues to handle bulk uploads asynchronously:

    // app/Jobs/UploadToCdn.php
    public function handle() {
        foreach ($this->files as $file) {
            Http::post("https://{$env('CDN_HOST')}/cdn/upload", [
                'file' => fopen($file->path, 'r')
            ]);
        }
    }
    

Integration Tips

  • Laravel Storage Integration: Extend Laravel’s Filesystem to proxy requests to the CDN.
    // app/Providers/AppServiceProvider.php
    public function register() {
        $this->app->singleton(\Illuminate\Contracts\Filesystem\Filesystem::class, function () {
            return new CdnFilesystem(
                new FilesystemAdapter(new CdnClient())
            );
        });
    }
    
  • Validation: Use Laravel’s validation rules to enforce file types/sizes before upload.
    $request->validate([
        'file' => 'required|file|mimes:jpg,png,pdf|max:10240',
    ]);
    
  • Logging: Log CDN responses for debugging:
    $response = Http::withOptions(['debug' => true])->post(...);
    

Gotchas and Tips

Pitfalls

  1. Authentication Failures

    • Ensure the .env CDN_PASS matches the plaintext password used in security:hash-password.
    • Verify the CDN_USER UUIDv7 is consistent across configurations.
  2. File Permissions

    • The public/upload directory must be writable by the web server user (e.g., unit:unit).
    • Debug with ls -la public/upload to confirm permissions.
  3. CORS Issues

    • If accessing the CDN from a web app, configure CORS on the CDN server to allow your domain:
      add_header 'Access-Control-Allow-Origin' 'https://your-app.com';
      
  4. Rate Limiting

    • The CDN may throttle requests. Implement exponential backoff in Laravel:
      use Symfony\Component\Mime\Part\DataPart;
      use Illuminate\Support\Facades\Http;
      
      $attempts = 0;
      $maxAttempts = 3;
      $delay = 100; // ms
      
      while ($attempts < $maxAttempts) {
          try {
              $response = Http::post(...);
              break;
          } catch (\Exception $e) {
              $attempts++;
              usleep($delay * pow(2, $attempts));
          }
      }
      

Debugging

  • Check CDN Logs: Access the CDN server logs (/var/log/nginx/error.log or similar) for failed requests.
  • Test Authentication:
    curl -u "$CDN_USER:$CDN_PASS" "https://$CDN_HOST/cdn/upload"
    
  • Validate Hashing:
    // Test if password matches
    $hasher = new Symfony\Component\PasswordHasher\Hasher\UserPasswordHasher();
    $isValid = $hasher->isPasswordValid(
        new User(['password' => $hashedPassword]),
        $plainPassword
    );
    

Extension Points

  1. Custom Storage Adapter Extend the CDN client to support additional features (e.g., presigned URLs):

    class CustomCdnClient extends \BaksDev\FilesCdn\Client {
        public function generatePresignedUrl(string $filename, int $expiry = 3600): string {
            // Implement logic to generate a presigned URL
        }
    }
    
  2. Webhook Integration Listen for file upload events via webhooks (if the CDN supports them) to trigger Laravel jobs:

    // routes/web.php
    Route::post('/cdn/webhook', function (Request $request) {
        UploadEvent::dispatch($request->json());
    });
    
  3. Fallback Mechanism Implement a fallback to local storage if the CDN is unavailable:

    public function getFileUrl(string $filename): string {
        try {
            return $this->cdn->getUrl($filename);
        } catch (\Exception $e) {
            return Storage::url("fallback/{$filename}");
        }
    }
    
  4. Configuration Overrides Override CDN settings dynamically (e.g., per-environment):

    // config/cdn.php
    return [
        'host' => env('CDN_HOST', 'cdn.default.host'),
        'timeout' => env('CDN_TIMEOUT', 30),
    ];
    
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.
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels