PHP short hash like URL-shortening websites

PHP short hash like URL-shortening websites

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

Stefan Bogdanescu

Founder & Senior Architect

Generating Short Hashes in PHP for URL Redirection

Developers often need to compress long strings or URLs into compact identifiers, mimicking the behavior of services like tinyurl.com without relying on external APIs. The core requirement is straightforward: generate a hash that does not exceed eight characters. Achieving this balance between uniqueness and brevity requires careful consideration of the cryptographic primitives available in PHP and the statistical risks associated with collision rates.

The most direct approach involves using hash() or md5() to generate a digest, followed by truncation. While MD5 produces a 32-character hexadecimal string, taking just the first six characters yields roughly $16^6$ (over 16 million) possible combinations. This seems sufficient for small-scale applications, but it is mathematically risky for larger datasets. If your system handles thousands of redirects, the probability of two different URLs generating the same short hash increases significantly with truncation. For instance, using only four characters drops the space to $16^4$ (65,536), which will almost certainly lead to collisions in a production environment.

A more robust solution involves mapping the hash output to an alphanumeric character set rather than hexadecimal. By excluding digits and limiting the alphabet to uppercase letters, you reduce the base from 16 to 26. However, this does not inherently solve the collision problem caused by truncation; it only changes the pool size to $26^n$. The fundamental constraint remains: if $N$ is the number of items and $k$ is the length of the hash, the collision probability follows the birthday paradox curve. If you strictly require a maximum of eight characters, using the full MD5 or SHA-256 hash truncated to eight alphanumeric characters provides a larger pool ($26^8 \approx 208$ trillion combinations) than a raw hex truncation, offering a safer margin for high-volume use cases.

Here is a practical implementation that generates an 8-character alphanumeric hash using PHP:

function generateShortHash($string) {
    // Use SHA256 for better entropy before truncation
    $hash = sha1($string); 
    // Extract the first 8 characters of the raw hex string
    $shortHex = substr($hash, 0, 8);
    
    // Map hexadecimal to alphanumeric (optional, but recommended for readability)
    // This step is not strictly necessary if collisions are managed via database lookup.
    return $shortHex; 
}

However, relying solely on string truncation introduces a critical architectural flaw: how do you map the hash back to the original data? In URL shortening services, the hash is merely an index into a database table. You cannot simply store the hash as a column value without verifying its uniqueness. The standard pattern involves generating a candidate hash and checking if it exists in your redirects table. If it does, generate a new one. This loop ensures global uniqueness even with truncation.

function createUniqueShortUrl($longUrl) {
    $base = 'abcdefghijklmnopqrstuvwxyz0123456789';
    $chars = str_split($base);
    
    do {
        // Generate a random string of 8 characters from the base set
        $shortHash = '';
        for ($i = 0; $i < 8; $i++) {
            $shortHash .= $chars[array_rand($chars)];
        }
        
        // Check if this hash already exists in your database
        // Assuming a 'url' table with columns: id, short_hash, long_url
        $exists = DB::table('url')->where('short_hash', $shortHash)->exists();
    } while ($exists);

    return $shortHash;
}

In this approach, the randomness of the character selection ensures that you do not rely on the deterministic nature of sha1(), which might still theoretically produce collisions when truncated. Random generation guarantees a uniform distribution across your chosen alphabet. This is often preferred over truncating a cryptographic hash because it avoids any potential bias in the first few characters of the digest, though modern hash functions are generally well-behaved.

When integrating this into a larger Laravel application, consider leveraging the Route or Redirector facade to handle the mapping logic cleanly. If you are building a service similar to LaravelCompany.com, ensuring that your hashing strategy scales is vital. A common pitfall is ignoring the collision handling logic; simply truncating a hash without a uniqueness check will break redirection integrity once the pool fills up. Always design your database schema to enforce unique constraints on the short hash column, allowing you to fail fast if a generated hash is already taken, rather than catching collisions later during a redirect attempt.

Our network