Home Backend Development PHP Problem How to convert long links into short links in php

How to convert long links into short links in php

Apr 19, 2023 am 09:16 AM

In the vast world of the Internet, long links have become an inevitable part of daily life. Long links not only make it difficult for people to remember, but they are also very unsightly in terms of text layout. So how to convert long links into short links? PHP is a widely used programming language. This article will introduce how to use PHP to simply convert long links into short links.

A brief introduction to short links

A short link is a special link based on the Internet. It uses a special algorithm to convert long links into short links, thereby improving the aesthetics and readability of the link. Readability and shareability. Short links are generally in the form of short strings, usually only 10 to 20 characters in length. After converting long links into short links, not only can it be more convenient to share and disseminate the link, but it can also better count the visits of the link.

How to generate short links using php

Generating short links needs to be divided into two steps. The first step is to design the short link generation algorithm, and the second step is to store the short links in the database. , then when querying, obtain the long link by parsing the short link and jump to it.

Design short link generation algorithm

Usually, the short link generation algorithm needs to meet the following requirements:

1. The generated short link must be unique and not repeated. .

2. The generated short link should be as close to a short string as possible.

3. The generated short link must be reversible, that is, the long link can be restored through the short link.

Currently, there are two commonly used short link algorithms. One is to encrypt long links to convert them into short links. Commonly used encryption algorithms include md5 and base64, but the shortness of this algorithm is The link length is long and will be repeated; another algorithm is to convert the long link into a decimal or hexadecimal short link and generate it based on the current timestamp and a custom value. The generation speed of this algorithm is It is faster, and the generated short links are shorter in length and will not be repeated.

Next, we introduce the PHP implementation method of using the second algorithm to generate short links.

First, we define some variables:

$url = 'http://www.example.com/longurl'; //待转换的长链接
$base = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; //定义62进制字符
$prefix = 'http://s.com/'; //自定义短链接前缀
Copy after login

Next, we need to convert the long link into a short link in decimal or 62 hexadecimal:

$hex = md5($url);
$hexLen = strlen($hex);
$subHexLen = $hexLen / 8;
$output = array();

for ($i = 0; $i < $subHexLen; $i++) {
    $subHex = substr($hex, $i * 8, 8);
    $int = 0x3FFFFFFF & (1 * (&#39;0x&#39; . $subHex));
    $out = &#39;&#39;;
    for ($j = 0; $j < 6; $j++) {
        $val = 0x0000003D & $int;
        $out .= $base[$val];
        $int = $int >> 5;
    }
    $output[] = $out;
}

$key = array_rand($output);
$shortUrl = $prefix . $output[$key];
Copy after login

In In the above code, we first use md5 to encrypt the long link, and then process the encrypted result and convert it into a decimal or hexadecimal short link. Next, one short link is selected from multiple short links by randomly generating a unique key value, and finally the custom prefix and the selected unique short link are spliced ​​into the final short link.

Storing the short link into the database

In the above code, we have generated the short link, but we have not yet stored it in the database. Here we use the mysql database to The code for storing short links in the database is as follows:

include 'config.php'; //包含数据库连接配置文件
$long_url = 'http://www.example.com/longurl'; //长链接

//生成短链接的代码
$hex = md5($long_url);
$hexLen = strlen($hex);
$subHexLen = $hexLen / 8;
$output = array();

for ($i = 0; $i < $subHexLen; $i++) {
    $subHex = substr($hex, $i * 8, 8);
    $int = 0x3FFFFFFF & (1 * (&#39;0x&#39; . $subHex));
    $out = &#39;&#39;;
    for ($j = 0; $j < 6; $j++) {
        $val = 0x0000003D & $int;
        $out .= $base[$val];
        $int = $int >> 5;
    }
    $output[] = $out;
}

$key = array_rand($output);
$short_url = $prefix . $output[$key];

//将短链接存储到数据库中
$insert_sql = "INSERT INTO `short_url` (`long_url`, `short_url`, `create_time`) VALUES ('{$long_url}', '{$short_url}', NOW())"; //将长链接和短链接插入数据库中
$conn->query($insert_sql); //执行插入操作
$conn->close(); //关闭数据库连接
Copy after login

In the above code, we define two variables long_url and short_url to store long links and short links respectively, and then insert sql statements to store long links and short links Insert into the short_url table. Among them, the create_time field stores the time when the short link was created, and the data type is DATETIME.

Jump to long link through short link

Finally, we need to parse the short link, query the corresponding long link from the database and jump. The code is implemented as follows:

include 'config.php'; //包含数据库连接配置文件
$short_url = 'http://s.com/abcd'; //短链接

//从数据库中查询出对应的长链接
$select_sql = "SELECT long_url FROM `short_url` WHERE `short_url`='{$short_url}'";
$result = $conn->query($select_sql); //执行查询操作
$row = $result->fetch_array(MYSQLI_ASSOC);

//跳转到长链接
if ($row) {
    $long_url = $row['long_url'];
    header('location:' . $long_url); //跳转到原来的长链接
    exit;
} else {
    echo '短链接不存在'; //如果短链接不存在,则输出短链接不存在
}
$conn->close(); //关闭数据库连接
Copy after login

In the above code, we first query the database using the short link as a parameter to find the corresponding long link. If it exists, the user will be jumped to the long link, otherwise the output short link does not exist.

Summary

php is a widely used programming language. By familiarizing yourself with the basic syntax and function library of php, you can easily realize the function of converting long links into short links. Although the algorithm for generating short links introduced in this article is not the most complex, it has good computing speed and link uniqueness, and is suitable for most application scenarios. It is recommended that readers improve the code according to actual needs to improve the stability and query speed of short link generation.

The above is the detailed content of How to convert long links into short links in php. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
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)

What are the best practices for deduplication of PHP arrays What are the best practices for deduplication of PHP arrays Mar 03, 2025 pm 04:41 PM

This article explores efficient PHP array deduplication. It compares built-in functions like array_unique() with custom hashmap approaches, highlighting performance trade-offs based on array size and data type. The optimal method depends on profili

Can PHP array deduplication take advantage of key name uniqueness? Can PHP array deduplication take advantage of key name uniqueness? Mar 03, 2025 pm 04:51 PM

This article explores PHP array deduplication using key uniqueness. While not a direct duplicate removal method, leveraging key uniqueness allows for creating a new array with unique values by mapping values to keys, overwriting duplicates. This ap

Does PHP array deduplication need to be considered for performance losses? Does PHP array deduplication need to be considered for performance losses? Mar 03, 2025 pm 04:47 PM

This article analyzes PHP array deduplication, highlighting performance bottlenecks of naive approaches (O(n²)). It explores efficient alternatives using array_unique() with custom functions, SplObjectStorage, and HashSet implementations, achieving

How to Implement message queues (RabbitMQ, Redis) in PHP? How to Implement message queues (RabbitMQ, Redis) in PHP? Mar 10, 2025 pm 06:15 PM

This article details implementing message queues in PHP using RabbitMQ and Redis. It compares their architectures (AMQP vs. in-memory), features, and reliability mechanisms (confirmations, transactions, persistence). Best practices for design, error

What Are the Latest PHP Coding Standards and Best Practices? What Are the Latest PHP Coding Standards and Best Practices? Mar 10, 2025 pm 06:16 PM

This article examines current PHP coding standards and best practices, focusing on PSR recommendations (PSR-1, PSR-2, PSR-4, PSR-12). It emphasizes improving code readability and maintainability through consistent styling, meaningful naming, and eff

What are the optimization techniques for deduplication of PHP arrays What are the optimization techniques for deduplication of PHP arrays Mar 03, 2025 pm 04:50 PM

This article explores optimizing PHP array deduplication for large datasets. It examines techniques like array_unique(), array_flip(), SplObjectStorage, and pre-sorting, comparing their efficiency. For massive datasets, it suggests chunking, datab

How Do I Work with PHP Extensions and PECL? How Do I Work with PHP Extensions and PECL? Mar 10, 2025 pm 06:12 PM

This article details installing and troubleshooting PHP extensions, focusing on PECL. It covers installation steps (finding, downloading/compiling, enabling, restarting the server), troubleshooting techniques (checking logs, verifying installation,

How to Use Reflection to Analyze and Manipulate PHP Code? How to Use Reflection to Analyze and Manipulate PHP Code? Mar 10, 2025 pm 06:12 PM

This article explains PHP's Reflection API, enabling runtime inspection and manipulation of classes, methods, and properties. It details common use cases (documentation generation, ORMs, dependency injection) and cautions against performance overhea

See all articles