Home > Backend Development > PHP Tutorial > 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
Release: 2024-10-19 11:18:29
Original
573 people have browsed it

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>
    Copy after login
  2. Convert an integer to a Base 36 string:

    <code class="php">$shortURL = base_convert($id, 10, 36);</code>
    Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template