search
HomeBackend DevelopmentPHP ProblemHow to convert long links into short links in php

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 > 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 > 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
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

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 Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

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 XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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 Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)