Short Hashing for URLs in PHP
Question:
How can I create short hashes from strings or files in PHP, similar to popular URL-shortening websites?
Answer:
Contrary to popular belief, URL shorteners like TinyURL do not use hashing algorithms. Instead, they employ integer conversions from various bases (e.g., Base 36 or 62) to represent numeric identifiers.
Using Base 36:
Convert a Base 36 string to an integer:
<code class="php">$id = intval($shortURL, 36);</code>
Convert an integer to a Base 36 string:
<code class="php">$shortURL = base_convert($id, 10, 36);</code>
This approach provides more flexibility and avoids hash collisions, allowing you to easily check for existing URLs and retrieve their corresponding IDs without exposing them to users. Base 36 integers yield a broader range of combinations than a typical hash would.
The above is the detailed content of How to Create Short Hash-Like IDs for URLs in PHP without Hashing. For more information, please follow other related articles on the PHP Chinese website!