PHP base_convert用于缩短URL

时间:2011-07-19 08:10:19

标签: php url

我想让我的网址更短,类似tinyurl,或任何其他网址缩短服务。我有以下类型的链接:

localhost/test/link.php?id=1000001
localhost/test/link.php?id=1000002

上述链接中的ID是自动递增来自db的行的ID。 上面的链接映射如下:

localhost/test/1000001
localhost/test/1000002

现在,我想缩短它们,而不是使用上面的长ID。我发现我可以使用base_convert()函数。例如:

print base_convert(100000000, 10, 36);

//output will be "1njchs"

看起来相当不错,但是我想问一下使用这个函数是否有任何不利(例如,性能缓慢或任何其他)或是否有更好的方法来做同样的事情(例如,使自己的函数生成随机ID字符串)?

感谢。

3 个答案:

答案 0 :(得分:4)

函数base_convert足够快,但如果你想做得更好,只需将编码的字符串存储在数据库中。

答案 1 :(得分:3)

使用base_convert(),您可以将字符串转换为更短的代码 然后使用intval()创建一个ID来存储数据库中的项目

我的代码段: -

$code = base_convert("long string", 10, 36);
$ID= intval($code ,36); 

答案 2 :(得分:0)

不幸的是,我对此处和其他地方的答案不满意base_convert()和其他基于浮点的转换策略因加密目的而失去了无法接受的精度。此外,大多数这些实现都无法处理足以用于加密应用的数字。以下提供了两种基本转换方法,对于大型碱基应该是安全的。例如,将base256(二进制字符串)转换为base85表示并再次返回。

使用GMP

您可以使用GMP来完成此操作,但需要将bin< - > hex转换为两次不需要的时间以及限制为base62。

<?php
// Not bits, bytes.
$data = openssl_random_pseudo_bytes(256);

$base62 = gmp_strval( gmp_init( bin2hex($data), 16), 62 );
$decoded = hex2bin( gmp_strval( gmp_init($base62, 62), 16 ));

var_dump( strcmp($decoded, $data) === 0 ); // true

纯PHP

如果你想超越base62到base85或稍微改善性能,你将需要以下内容。

<?php

/**
* Divide a large number represented as a binary string in the specified base
* and return the remainder.
* 
* @param string &$binary
* @param int $base
* @param int $start
*/
function divmod(&$binary, $base, $divisor, $start = 0)
{
    /** @var int $size */
    $size = strlen($binary);

    // Do long division from most to least significant byte, keep remainder.
    $remainder = 0;
    for ($i = $start; $i < $size; $i++) {
        // Get the byte value, 0-255 inclusive.
        $digit = ord($binary[$i]);

        // Shift the remainder left by base N bits, append the last byte.
        $temp = ($remainder * $base) + $digit;

        // Calculate the value for the current byte.
        $binary[$i] = chr($temp / $divisor);

        // Carry the remainder to the next byte.
        $remainder = $temp % $divisor;
    }

    return $remainder;
}

/**
* Produce a base62 encoded string from a large binary number.
* 
* @param string $binary
* return string
*/
function encodeBase62($binary)
{
    $charMap = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $base = strlen($charMap);

    $size = strlen($binary);
    $start = $size - strlen(ltrim($binary, "\0"));

    $encoded = "";
    for ($i = $start; $i < $size; ) {
        // Do long division from most to least significant byte, keep remainder.
        $idx = divmod($binary, 256, $base, $i);

        $encoded = $charMap[$idx] . $encoded;

        if (ord($binary[$i]) == 0) {
            $i++; // Skip leading zeros produced by the long division.
        }
    }

    $encoded = str_pad($encoded, $start, "0", STR_PAD_LEFT);

    return $encoded;
}

/**
* Produce a large binary number from a base62 encoded string.
* 
* @param string $ascii
* return string
*/
function decodeBase62($ascii)
{
    $charMap = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $base = strlen($charMap);

    $size = strlen($ascii);
    $start = $size - strlen(ltrim($ascii, "0"));

    // Convert the ascii representation to binary string.
    $binary = "";
    for ($i = $start; $i < $size; $i++) {
        $byte = strpos($charMap, $ascii[$i]);
        if ($byte === false) {
            throw new OutOfBoundsException("Invlaid encoding at offset '{$ascii[$i]}'");
        }

        $binary .= chr($byte);
    }

    $decode = "";
    for ($i = 0; $i < $size; ) {
        // Do long division from most to least significant byte, keep remainder.
        $idx = divmod($binary, $base, 256, $i);

        $decode = chr($idx) . $decode;

        if (ord($binary[$i]) == 0) {
            $i++; // Skip leading zeros produced by the long division.
        }
    }

    $decode = ltrim($decode, "\0");
    $decode = str_pad($decode, $start, "\0", STR_PAD_LEFT);

    return $decode;
}

// Not bits, bytes.
$data = openssl_random_pseudo_bytes(256);

$base62 = encodeBase62($data);
$decoded = decodeBase62($base62);

var_dump( strcmp($decoded, $data) === 0 ); // true