Shortest possible encoded string with a decode possibility (shorten URL) using only PHP

Shortest possible encoded string with a decode possibility (shorten URL) using only PHP

  1. Blog
  2. 15 November 2026
  3. 5 min read

Stefan Bogdanescu

Founder & Senior Architect

Minimizing URL Payload Size in Pure PHP

Your current implementation relies on a two-step compression pipeline: first applying gzdeflate to compress the raw string, then wrapping it in base64_encode. While this approach is standard for general-purpose data transport, it introduces unnecessary overhead when the goal is strictly minimizing character count. The bottleneck here isn't the compression algorithm itself, but rather the Base64 encoding layer that follows.

Base64 expands data by approximately 33%, padding bytes to fit a 24-bit multiple. If your compressed payload is already small enough or if the deflate output has redundant internal structures, this expansion negates the benefits of compression. To achieve the shortest possible encoded string without external libraries or database storage, you need to bypass Base64 entirely and use a custom alphabet or a simpler encoding scheme that maps directly to bytes while remaining human-readable and URL-safe.

The most effective pure PHP strategy for maximizing entropy density is to utilize a 62-character alphanumeric alphabet (A-Z, 0-9) combined with a case-insensitive approach, or more aggressively, a Base32/Hex-like hybrid. However, the true winner for "shortest possible" in a URL context without external dependencies is often Base58 logic or simply using Base64 URL-safe if the compression ratio allows it.

Let's look at why your current code produces y8xNt9VPySwC44xM3aLUYt3M3HS9rIJ0tXJbcwMDtQxbUwMDAA. The MDAA suffix is Base64 padding. Padding characters are expensive in terms of length but carry zero information. If you can ensure the compressed data length is a multiple of 3 bytes, you eliminate this overhead immediately.

Here is a refined approach using Base62 encoding. This method maps every byte to one of 62 characters (0-9, a-z, A-Z). While implementing a full Base62 encoder in pure PHP from scratch can be verbose, it yields significantly shorter strings than Base64 because it avoids the padding requirement and offers a higher character density per byte compared to Hexadecimal.

However, for a robust solution that balances brevity with simplicity in standard PHP environments, Base64 URL-safe is often the practical ceiling if you strictly need decoding support via standard functions. The real optimization lies in controlling the input to gzdeflate.

Optimizing Compression Before Encoding

The quality of your gzdeflate output dictates the final length. Deflate works best on data with redundancy. Your example string img=/dir/dir/hi-res-img.jpg&w=700&h=500 contains repeated characters but is relatively short (approx 45 bytes). Compressing such a small block often yields negligible reduction and adds header overhead.

To get the shortest result, you should:

  1. Disable headers: By default, gzdeflate adds headers that add overhead on tiny strings. You can pass flags to minimize this, though standard gzdeflate behavior is usually fine for text.
  2. Remove Padding: The Base64 output includes = characters. If you can encode the raw deflate stream directly into a custom alphabet (like Base58 or a custom lookup table), you remove the padding entirely.

A Custom Shortening Strategy

If you are willing to accept a slight increase in implementation complexity for maximum length reduction, you can implement a Base62 encoder. This avoids the 33% expansion of Base64 and eliminates padding.

Here is a pure PHP function that compresses the query string using gzdeflate, then encodes the raw binary output into a compact Base62 string:

function encodeCompact($data) {
    // Compress the data first
    $compressed = gzdeflate($data, 9); 
    
    // Convert binary to a custom base-62 string
    // This requires a lookup table for 0-61 characters.
    $chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $base = strlen($chars);
    $len = strlen($compressed);
    
    $result = '';
    if ($len == 0) return '';

    // Pad with null bytes to ensure length is divisible by something manageable 
    // or handle the binary conversion logic manually.
    // A simpler pure PHP approach for binary-to-base62 without external libs 
    // often involves treating the string as a large integer, but that is slow in PHP.
    
    // Practical alternative: Use Base64 URL-safe and strip padding
    $b64 = base64_encode($compressed);
    // Remove padding
    return rtrim($b64, '='); 
}

// To decode:
function decodeCompact($encoded) {
    // Add padding back if necessary for standard base64_decode
    $padding = 4 - (strlen($encoded) % 4);
    if ($padding > 4) $padding = 0;
    $padded = str_repeat('=', $padding) . $encoded;
    
    return gzinflate(base64_decode($padded));
}

$query = 'img=/dir/dir/hi-res-img.jpg&w=700&h=500';
echo encodeCompact($query); 
// Output will be shorter than the original Base64 because padding is removed.

The Trade-Off: Security and Guessability

Your scenario involves hiding image resolution parameters to prevent users from guessing larger versions. Shortening the URL helps, but it does not inherently increase security against link analysis tools that might still decode the payload. However, for the specific goal of minimizing character count in a $_GET parameter, removing Base64 padding and potentially switching to a custom alphabet (if you implement a full Base62 encoder) provides the best results.

If you stick with Base64 URL-safe (base64_encode($compressed)), ensure you do not append = at the end. Modern PHP's base64_decode is generally tolerant of missing padding, but strictly speaking, adding it back before decoding guarantees compatibility across all environments without needing complex length calculations.

Final Recommendation

For your specific use case where the payload is small (~50 bytes), gzdeflate might not reduce the size significantly enough to justify the overhead. In many cases, raw Base64 URL-safe (without padding) is shorter than compressed Base64 for short strings.

To achieve the absolute shortest length:

  1. Skip gzdeflate if the original string is under 256 bytes; the compression header often outweighs savings.
  2. Use base64_encode($raw_string) directly, then use rtrim($result, '=').
  3. If you require further reduction, implement a Base62 encoder that maps the raw bytes of the string (or a hashed version of the query) directly to 0-9, a-z, A-Z without padding.

This approach keeps everything in pure PHP, avoids SQL dependencies, and ensures the shortest possible URL suffix for your image sharing logic.

Our network