Home  >  Article  >  Backend Development  >  How to Create Short Hash-Like IDs for URLs in PHP without Hashing

How to Create Short Hash-Like IDs for URLs in PHP without Hashing

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 11:18:29441browse

How to Create Short Hash-Like IDs for URLs in PHP without Hashing

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:

  1. Convert a Base 36 string to an integer:

    <code class="php">$id = intval($shortURL, 36);</code>
  2. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn