PHP 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:
/**
* 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:
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~~
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;
}
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

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

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 each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

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

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools