PHP网址缩短算法 [英] PHP URL Shortening Algorithm

查看:159
本文介绍了PHP网址缩短算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以推荐一个preferred算法使用网址缩短?我编码使用PHP。起初,我想过写东西,将开始在一个字符,如a和遍历请求,在数据库中创建记录,因此有增加字符到B,C,D ...... A,B等为合适的。

Could anyone recommend a preferred algorithm to use for URL shortening? I'm coding using PHP. Initially I thought about writing something that would start at a character such as "a" and iterate through requests, creating records in a database and therefore having to increment the character to b, c, d ... A, B and so on as appropriate.

不过,我明白了,这种算法可能是pretty的重/笨拙,有可能是一个更好的方式来做到这一点。

However it dawned on me that this algorithm could be pretty heavy/clumsy and there could be a better way to do it.

我读了一下周围的谷歌和一些人似乎从数据库的ID柱基转换为那样做。这是不是我太熟悉了。

I read around a bit on Google and some people seem to be doing it with base conversion from the database's ID column. This isn't something I'm too familiar with.

可能有人阐述,并给我解释如何做到这一点的?一对夫妇的code例子将是巨大的,太。

Could someone elaborate and explain to me how this would work? A couple of code examples would be great, too.

我显然不希望一个完整的解决方案,因为我想这样做我自己去学习,而只是一个解释/伪$ c。关于如何做到这一点的工作$ C是优秀的。

I obviously don't want a complete solution as I would like to learn by doing it myself, but just an explanation/pseudo-code on how this would work would be excellent.

推荐答案

大多数缩短服务只使用递增每进入一个计数器,并从10基转换为64。

Most shortening services just use a counter that is incremented with every entry and convert the base from 10 to 64.

在PHP中的实现可能是这样的:

An implementation in PHP could look like this:

function encode($number) {
    return strtr(rtrim(base64_encode(pack('i', $number)), '='), '+/', '-_');
}
function decode($base64) {
    $number = unpack('i', base64_decode(str_pad(strtr($base64, '-_', '+/'), strlen($base64) % 4, '=')));
    return $number[1];
}

$number = mt_rand(0, PHP_INT_MAX);
var_dump(decode(encode($number)) === $number);

连接code 函数接受一个整数,将其转换成字节( ),EN codeS它与BASE-64编码(的 base64_en code ),修剪尾随填充 = RTRIM ),并替换字符 + / - _ 分别为(的 strtr函数的效率 )。该德code 函数的反函数连接code 和做完全相反的(除加入尾随填充)。

The encode function takes an integer number, converts it into bytes (pack), encodes it with the Base-64 encoding (base64_encode), trims the trailing padding = (rtrim), and replaces the characters + and / by - and _ respectively (strtr). The decode function is the inverse function to encode and does the exact opposite (except adding trailing padding).

额外使用 strtr函数的效率是要转换的原BASE-64字母 URL和文件名安全字母 + / 必须是EN codeD用百分比编码。

The additional use of strtr is to translate the original Base-64 alphabet to the URL and filename safe alphabet as + and / need to be encoded with the Percentage-encoding.

这篇关于PHP网址缩短算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆