Home  >  Article  >  Backend Development  >  How to convert long links into short links in php

How to convert long links into short links in php

PHPz
PHPzOriginal
2023-04-19 09:16:571292browse

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/'; //自定义短链接前缀

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];

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(); //关闭数据库连接

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(); //关闭数据库连接

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:
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