Home  >  Article  >  Backend Development  >  A PHP function to generate short URLs

A PHP function to generate short URLs

巴扎黑
巴扎黑Original
2016-12-07 16:32:592565browse

Everyone is familiar with short URLs, especially applications on Weibo that have made it popular. In fact, it is very simple to implement this function.

<?php
/**
 * 短网址
 */
 
function urlShort($url){
    $url= crc32($url);
    $result= sprintf("%u", $url);
    $sUrl= &#39;&#39;;
    while($result>0){
        $s= $result%62;
        if($s>35){
            $s= chr($s+61);
        } elseif($s>9 && $s<=35){
            $s= chr($s+ 55);
        }
        $sUrl.= $s;
        $result= floor($result/62);
    }
    return $sUrl;
}
 
$url = &#39;www.qttc.net&#39;;
$sUrl = urlShort($url);
 
echo &#39;<meta charset="utf-8" />&#39;;
echo &#39;网址:&#39;.$url.&#39;<br />&#39;;
echo &#39;短网址:&#39;.$sUrl;
 
?>

The above result output:
Website: www.qttc.net
Short URL: SwOOy3
The short URL can be stored in the database and make a mapping relationship. Together with nginx rewriting rules, short URL generation, restoration, and jump functions can be realized.

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