Home Backend Development PHP Tutorial PHP short link algorithm collection and analysis_PHP tutorial

PHP short link algorithm collection and analysis_PHP tutorial

Jul 21, 2016 pm 03:21 PM
h php and analyze Weibo collect Sina short algorithm Link

I won’t talk about the short link, everyone already knows it. The short link is as follows:
Sina Weibo http://t.cn/SVpONM
Tencent Weibo http://url.cn/302yor
Yun.io http://d.yun.io/PNri2v
Benefits of short links: 1. Content requirements; 2. User-friendly; 3. Easy management.
How to implement it, there are roughly three steps:
1. Define a URL mapping algorithm that can map long URLs into short strings;
2. Use a storage (database? NoSQL?) to store Completed mapping;
3. Implement your own URL mapping algorithm;
Generally speaking, the third step is a headache for us. How to map a long URL string into a shorter string? . I have summarized three methods:
Common implementation
I think everyone has learned about the conversion between decimal and binary, or the conversion between decimal and hexadecimal. In order to be shorter, we can use 62-digit system. , transcode a numeric ID into a short string.
The disadvantage of this approach is that there is no way to ensure that all links are of a fixed length in bits, and in the case of high concurrency, how to ensure rapid distribution is a problem.
Specific implementation method:

Copy code The code is as follows:

/**
* Use hexadecimal to encode digital IDs for short links. The disadvantage is that each short link cannot be guaranteed to be of fixed length
*
* @author wanshiqiang
* @param integer $integer
* @param string $base
*/
private function getShortenedURLFromID ($integer, $base = ALLOWED_CHARS)
{
$length = strlen($base);
while($integer > $length - 1)
{
$ out = $base[fmod($integer, $length)] . ​​$out;
$integer = floor( $integer / $length );
}
return $base[$integer] . $out ;
}
/**
* Decode the hexadecimal encoded short link
*
* @author wangshiqiang
* @param string $string
* @param string $base
*/
private function getIDFromShortenedURL ($string, $base = ALLOWED_CHARS)
{
$length = strlen($base);
$size = strlen($string) - 1;
$string = str_split($string);
$out = strpos($base, array_pop($string));
foreach($string as $ i => $char)
{
$out += strpos($base, $char) * pow($length, $size - $i);
}
return $out;
}

Literary implementation
Algorithm description: Use 6 characters to represent short links, we use 'a'-'z','0'-'5 in ASCII characters ', a total of 32 characters are used as a set. Each character has 32 states. Six characters can represent 32^6 (1073741824). So how to get these six characters is described as follows:
Perform Md5 on the incoming long URL to get a 32-bit character String, this string changes a lot, is 16 to the 32nd power, and can basically guarantee uniqueness. Divide these 32 bits into four parts, each part has 8 characters. At this time, the probability becomes 16 to the 8th power, which is 4294967296. The probability of collision of this number is also relatively small. The key is the subsequent processing. We think of this 8-bit character as a hexadecimal integer, that is, 1*('0x'.$val), and then take 0-30 bits, every group of 5, calculate its integer value, and then map it to our From the prepared 32 characters, you can finally get a 6-digit short link address.
PHP implementation is as follows:
Copy code The code is as follows:

function shorten( $long_url )
{
$base32 = "abcdefghijklmnopqrstuvwxyz012345";
$hex = md5( $long_url );
$hexLen = strlen( $hex );
$subHexLen = $hexLen / 8;
$output = array();
for( $i = 0; $i < $subHexLen; $i++ )
{
$subHex = substr( $hex, $i * 8, 8 );
$subHex = 0x3FFFFFFF & ( 1 * ('0x' . $subHex ) );
  $out = '';
for( $j = 0; $j < 6; $j++ )
{
$val = 0x0000001F & $int;
$out .= $base32[$val];
$int = $int >> 5;
}
$output[] = $out;
}
return $output;
}

Second implementation
The following function uses a purely random method to generate a short link, although We can use query operations to ensure that short links are not reused, but... Is this really reliable~~
Copy code The code is as follows:

function random($length, $pool = '') {
$random = '';
if (empty($pool)) { $pool = 'abcdefghkmnpqrstuvwxyz'; $pool .=
'23456789'; }
srand ((double)microtime()*1000000);
for($i = 0; $i < $length; $i++) { $random .=
substr($pool,(rand()%(strlen ($pool))), 1); }
return $random;
}

Technorati tags: short link, Short Url, mapping, hash

Reference:

1. Analysis of the principle of Weibo short address

2. Principles and functions of Weibo short domain names

3. Yours.org

4. Free PHP URL Shorten script that kicks ass

5. PHP Short Url Algorithm Implementation

6. Implement your own short URL

7. Preliminary summary of short URL algorithm

8. Short Url implementation

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324818.htmlTechArticleI won’t talk about the short link. Everyone already knows it. The short link is as follows: Sina Weibo http //t.cn/SVpONM Tencent Weibo http://url.cn/302yor Yun.io http://d.yun.io/PNri2v Short link...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24
PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles