Home Backend Development PHP Tutorial Summary of methods for generating short URLs using PHP

Summary of methods for generating short URLs using PHP

Jun 01, 2018 pm 05:47 PM
php Summarize method

本文给大家汇总介绍了3种使用php生成短网址的方法,第一种是PHP+MySQl实现短网址的生成和读取,第二种是php+ini方式,第三种跟第一种有些类似,各有利弊,小伙伴们可以根据自己的项目需求来选择。

正常的网址带上参数的那种可能会很长,尤其是我们在印刷纸质品如企业宣传册中要印上某个长的url的话非常难看,而且也没几个人会去记这个网址,虽然现在可以用扫二维码的方式打开长网址。但是人们可以使用短网址来实现优美的链接,尤其是有字数限制的应用如微博。

短网址的实现原理就是有一个数据表会配置文件将短网址和实际网址进行对应,当请求某个短网址时,程序跳转到对应的实际网址上去,从而实现网址的访问。

方案1:PHP+MySQl实现短网址的生成和读取

常规的方案我们将生成好的短网址和原网址对应到一张数据表中,然后供读取使用。我们先来看如何生成唯一的短网址。

//生成短网址 
function code62($x){ 
  $show=''; 
  while($x>0){ 
    $s=$x % 62; 
    if ($s>35){ 
      $s=chr($s+61); 
    }elseif($s>9&&$s<=35){ 
      $s=chr($s+55); 
    } 
    $show.=$s; 
    $x=floor($x/62); 
  } 
  return $show; 
} 
function shorturl($url){ 
  $url=crc32($url); 
  $result=sprintf("%u",$url); 
  return code62($result); 
} 
echo shorturl(&#39;http://www.jb51.net/&#39;); 
//1EeIv2
Copy after login

使用以上PHP代码可以生成唯一的6位的短网址,然后我们将生成的短网址与原网址一起写入到MySQL表中,插入数据库的代码这里我就不写了,这是PHP基础。
接着,我们有一个link.php用来接收读取url并实现真实跳转。

include_once(&#39;connect.php&#39;); //连接数据库 
$url = $_GET[&#39;url&#39;]; 
if(isset($url) && !empty($url)){ 
  $sql = "select url from shorturl where codeid=&#39;$url&#39;"; 
  $query = mysql_query($sql); 
  if($row=mysql_fetch_array($query)){ 
    $real_url = $row[&#39;url&#39;]; 
    header(&#39;Location: &#39; . $real_url); 
  }else{ 
    header(&#39;HTTP/1.0 404 Not Found&#39;); 
    echo &#39;Unknown link.&#39;; 
  } 
}else{ 
  header(&#39;HTTP/1.0 404 Not Found&#39;); 
  echo &#39;Unknown link.&#39;; 
}
Copy after login

代码中,如果得到短网址对应的真实url,会使用header跳转到真实的页面上去,否则返回404代码。这样我们可以使用如: http://yourdomain/link.php?url=xxx来实现短网址访问。

继续,我们使用URL rewrite即重写功能来实现诸如可以通过地址:http://yourdomain/xxx 来访问。

以下是rewrite规则:

#Apache规则: 
RewriteRule ^/(.*)$ /link.php?url=$1 [L] 
 
#如果使用nginx,规则这样写: 
rewrite ^/(.*)$ /link.php?url=$1 last;
Copy after login

方案2:PHP+ini实现短网址技术

对于方案1使用数据库的做法好处就是操作方便,而大量短网址查询需要做优化。而方案2则放弃数据库,使用ini配置,我们将短网址和真实网址配置在ini文件中,PHP直接通过parse_ini_file()读取ini文件,几行代码就可以实现短网址的跳转。
links.ini文件像这样配置:

baidu  = https://www.baidu.com/ 
qq    = http://www.qq.com/ 
hw    = http://www.hw.com/ 
dm    = http://www.dm.com/view-blog-362.html
Copy after login

而index.php的代码可以这样写:

$links = parse_ini_file(&#39;links.ini&#39;); 
 
if(isset($_GET[&#39;l&#39;]) && array_key_exists($_GET[&#39;l&#39;], $links)){ 
  header(&#39;Location: &#39; . $links[$_GET[&#39;l&#39;]]); 
} 
else{ 
  header(&#39;HTTP/1.0 404 Not Found&#39;); 
  echo &#39;Unknown link.&#39;; 
}
Copy after login

当然,我们还需要配置下rewrite规则。

#Apache规则: 
RewriteRule ^/(.*)$ /index.php?l=$1 [L] 
 
#如果使用nginx,规则这样写: 
rewrite ^/(.*)$ /index.php?l=$1 last;
Copy after login

好了,我们现在访问网址:http://demo.jb51.net/dm,它直接跳转到实际网址:http://www.jb51.net/view-blog-362.html。
相比来说,第二种方案适合小型的应用,你还可以把url地址做成数组形式保存,还可以做一个管理界面专门维护这些短网址。

第三种方案:php版的短链接生成方法

<?php
function shorturl($input) {
$base32 = array (
&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;, &#39;h&#39;,
&#39;i&#39;, &#39;j&#39;, &#39;k&#39;, &#39;l&#39;, &#39;m&#39;, &#39;n&#39;, &#39;o&#39;, &#39;p&#39;,
&#39;q&#39;, &#39;r&#39;, &#39;s&#39;, &#39;t&#39;, &#39;u&#39;, &#39;v&#39;, &#39;w&#39;, &#39;x&#39;,
&#39;y&#39;, &#39;z&#39;, &#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;, &#39;4&#39;, &#39;5&#39;
);
 
$hex = md5($input);
$hexLen = strlen($hex);
$subHexLen = $hexLen / 8;
$output = array();
 
for ($i = 0; $i < $subHexLen; $i++) {
//把加密字符按照8位一组16进制与0x3FFFFFFF(30位1)进行位与运算
$subHex = substr ($hex, $i * 8, 8);
$int = 0x3FFFFFFF & (1 * (&#39;0x&#39;.$subHex));
$out = &#39;&#39;;
 
for ($j = 0; $j < 6; $j++) {
 
//把得到的值与0x0000001F进行位与运算,取得字符数组chars索引
$val = 0x0000001F & $int;
$out .= $base32[$val];
$int = $int >> 5;
}
 
$output[] = $out;
}
 
return $output;
}
?>
Copy after login

总结:

用户访问短网址 时的过程:

1、浏览器访问短网址http://short.cn/Xvdf23,经过DNS解析会指向到http://short.cn的服务器。
2、服务器根据短网址中的ID字段查找数据库,返回原始网址。
3、重定向到上面返回的原始网址

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

PHP字符串逆序排列实现方法

PHP使用递归算法无限遍历数组的方法

php 实现扫描二维码下载跳转的方法

The above is the detailed content of Summary of methods for generating short URLs using 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles