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

Base64Url Laravel Package

spomky-labs/base64url

Fast RFC 4648 Base64 URL-safe encoder/decoder for PHP. Lightweight library to encode/decode URL-safe Base64 strings with high performance, compatible with PHP 7.1+. Ideal for JWT, web tokens, and URL parameters.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require spomky-labs/base64url
    

    No additional configuration is required—just autoload the package.

  2. First Use Case Encode a string to Base64URL (e.g., for JWT tokens, API keys, or URL-safe data):

    use SpomkyLabs\Base64Url\Base64Url;
    
    $encoder = new Base64Url();
    $encoded = $encoder->encode('Hello, World!');
    // Output: "SGVsbG8sIFdvcmxkIQ=="
    

    Decode it back:

    $decoded = $encoder->decode($encoded);
    // Output: "Hello, World!"
    
  3. Where to Look First

    • Class Documentation (if available; check GitHub for legacy projects).
    • Focus on Base64Url::encode() and Base64Url::decode() methods.
    • For edge cases, review the Base64Url constructor (e.g., padding options).

Implementation Patterns

Core Workflows

  1. JWT Token Handling Encode/decode payloads for JWTs (replace base64_encode/base64_decode):

    $payload = json_encode(['user_id' => 123, 'role' => 'admin']);
    $encodedPayload = $encoder->encode($payload);
    // Use $encodedPayload in JWT generation (e.g., with `firebase/php-jwt`).
    
  2. URL-Safe API Keys Store or transmit API keys in URLs (e.g., /api/v1?key=ENCODED_KEY):

    $apiKey = 'sk_live_123abc';
    $safeKey = $encoder->encode($apiKey);
    // URL-safe: `/api/v1?key=czsxX3xpdnFfMTIzYWJj`
    
  3. Database Storage Store binary data (e.g., hashes) in text fields:

    $hash = hash('sha256', 'secret');
    $dbValue = $encoder->encode($hash);
    // Later: $originalHash = $encoder->decode($dbValue);
    

Integration Tips

  • Laravel Facades (Optional) Create a facade for cleaner syntax:

    // app/Providers/AppServiceProvider.php
    public function boot()
    {
        $this->app->bind('base64url', function () {
            return new Base64Url();
        });
    }
    

    Usage:

    $encoded = app('base64url')->encode('data');
    
  • Service Layer Encapsulate encoding/decoding in a service:

    class ApiKeyService {
        protected $encoder;
    
        public function __construct(Base64Url $encoder) {
            $this->encoder = $encoder;
        }
    
        public function generateSafeKey(string $key): string {
            return $this->encoder->encode($key);
        }
    }
    
  • Validation Use with Laravel’s validation:

    $request->validate([
        'encoded_key' => 'required|string',
    ]);
    $decodedKey = $encoder->decode($request->encoded_key);
    

Gotchas and Tips

Pitfalls

  1. Padding Handling

    • The package automatically strips padding (= characters) during encoding.
    • Decoding requires padding if the input lacks it (e.g., from URLs). Use:
      $decoded = $encoder->decode($encoded, false); // Skip padding check (not recommended).
      
    • Best Practice: Always ensure padding is present before decoding (e.g., add it manually or use str_pad).
  2. Non-String Inputs

    • The encoder expects strings. Non-string inputs (e.g., null, objects) will throw errors.
    • Fix: Cast inputs explicitly:
      $encoder->encode((string) $variable);
      
  3. Binary Data

    • For binary data (e.g., file contents), use base64_encode first, then this library:
      $binaryData = file_get_contents('image.png');
      $encoded = $encoder->encode(base64_encode($binaryData));
      
  4. URL Safety Assumptions

    • The library replaces + with - and / with _, but does not URL-encode other special characters (e.g., ~, ?).
    • For URLs, combine with rawurlencode:
      $safeForUrl = rawurlencode($encoder->encode('key=value'));
      

Debugging

  • Decoding Failures

    • If decoding throws InvalidArgumentException, check:
      1. Input contains only [A-Z0-9_-] (Base64URL alphabet).
      2. Input length is a multiple of 4 (add padding if needed).
      3. Input isn’t corrupted (e.g., truncated during transmission).
  • Character Mismatches

    • Compare encoded strings with base64_encode output to spot discrepancies:
      var_dump(
          base64_encode('test'),       // "dGVzdA=="
          $encoder->encode('test')    // "dGVzdA==" (should match)
      );
      

Extension Points

  1. Custom Alphabets

    • Extend the class to support non-standard alphabets (e.g., for custom encoding schemes):
      class CustomBase64Url extends Base64Url {
          protected $alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
      
          public function __construct() {
              parent::__construct();
              $this->setAlphabet($this->alphabet);
          }
      }
      
  2. Padding Strategies

    • Override padding behavior in the constructor:
      $encoder = new Base64Url();
      $encoder->setPadding(false); // Disable padding (not recommended for decoding).
      
  3. Performance

    • For bulk operations, cache the encoder instance (it’s stateless but instantiation has overhead):
      $encoder = new Base64Url(); // Reuse this instance.
      

Laravel-Specific Tips

  • Cached Config Store encoded values in config/cache (e.g., API keys):

    config(['services.api.key' => $encoder->encode('secret_key')]);
    
  • Encrypted Storage Combine with Laravel’s encryption for sensitive data:

    $encoded = $encoder->encode('secret');
    $encrypted = encrypt($encoded);
    
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui