search
HomeBackend DevelopmentPHP TutorialPHP short link algorithm collection and analysis_PHP tutorial

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 {
$subHex = substr( $hex, $i * 8, 8 );
$subHex = 0x3FFFFFFF & ( 1 * ('0x' . $subHex ) );
  $out = '';
for( $j = 0; $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 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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.