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

Video Face Swap

Video Face Swap

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

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)

PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. PHP 8 JIT (Just-In-Time) Compilation: How it improves performance. Mar 25, 2025 am 10:37 AM

PHP 8's JIT compilation enhances performance by compiling frequently executed code into machine code, benefiting applications with heavy computations and reducing execution times.

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. OWASP Top 10 PHP: Describe and mitigate common vulnerabilities. Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP Secure File Uploads: Preventing file-related vulnerabilities. PHP Secure File Uploads: Preventing file-related vulnerabilities. Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Encryption: Symmetric vs. asymmetric encryption. PHP Encryption: Symmetric vs. asymmetric encryption. Mar 25, 2025 pm 03:12 PM

The article discusses symmetric and asymmetric encryption in PHP, comparing their suitability, performance, and security differences. Symmetric encryption is faster and suited for bulk data, while asymmetric is used for secure key exchange.

How do you retrieve data from a database using PHP? How do you retrieve data from a database using PHP? Mar 20, 2025 pm 04:57 PM

Article discusses retrieving data from databases using PHP, covering steps, security measures, optimization techniques, and common errors with solutions.Character count: 159

PHP Authentication & Authorization: Secure implementation. PHP Authentication & Authorization: Secure implementation. Mar 25, 2025 pm 03:06 PM

The article discusses implementing robust authentication and authorization in PHP to prevent unauthorized access, detailing best practices and recommending security-enhancing tools.

What is the purpose of prepared statements in PHP? What is the purpose of prepared statements in PHP? Mar 20, 2025 pm 04:47 PM

Prepared statements in PHP enhance database security and efficiency by preventing SQL injection and improving query performance through compilation and reuse.Character count: 159

What is the purpose of mysqli_query() and mysqli_fetch_assoc()? What is the purpose of mysqli_query() and mysqli_fetch_assoc()? Mar 20, 2025 pm 04:55 PM

The article discusses the mysqli_query() and mysqli_fetch_assoc() functions in PHP for MySQL database interactions. It explains their roles, differences, and provides a practical example of their use. The main argument focuses on the benefits of usin

See all articles