PHP随机名而不是序列

时间:2018-05-21 17:10:11

标签: php

我有一个基本的网址缩短脚本,但我遇到了问题。每次我输入新网址以缩短脚本时,只需将下一个字母添加到数据库(即http://www.both.com/a,然后http://www.both.com/b,然后http://www.both.com/c等。问题是我不希望人们只需按顺序查看这些链接。我怎样才能使每个新网址都有一个随机的6位数字和数字名称?另外,我想让alpha都是随机的大写和小写。

<?php

require 'config.php';

header('Content-Type: text/plain;charset=UTF-8');

$url = isset($_GET['url']) ? urldecode(trim($_GET['url'])) : '';

 if (in_array($url, array('', 'about:blank', 'undefined', 'http://localhost/'))) {
die('Enter a URL.');
}


if (strpos($url, SHORT_URL) === 0) {
die($url);
}

function nextLetter(&$str) {
$str = ('z' == $str ? 'a' : ++$str);
}

function getNextShortURL($s) {
$a = str_split($s);
$c = count($a);
if (preg_match('/^z*$/', $s)) { // string consists entirely of `z`
    return str_repeat('a', $c + 1);
}
while ('z' == $a[--$c]) {
    nextLetter($a[$c]);
}
nextLetter($a[$c]);
return implode($a);
}

$db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE);
$db->set_charset('utf8mb4');

$url = $db->real_escape_string($url);

$result = $db->query('SELECT slug FROM redirect WHERE url = "' . $url . '" LIMIT 1');
if ($result && $result->num_rows > 0) { // If there’s already a short URL for this URL
die(SHORT_URL . $result->fetch_object()->slug);
} else {
$result = $db->query('SELECT slug, url FROM redirect ORDER BY date DESC, slug DESC LIMIT 1');
if ($result && $result->num_rows > 0) {
    $slug = getNextShortURL($result->fetch_object()->slug);
    if ($db->query('INSERT INTO redirect (slug, url, date, hits) VALUES ("' . $slug . '", "' . $url . '", NOW(), 0)')) {
        header('HTTP/1.1 201 Created');
        echo SHORT_URL . $slug;
        $db->query('OPTIMIZE TABLE `redirect`');
    }
}
}

?>

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

function generateString($length) {
    $alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $alphabetLength = strlen($alphabet);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $alphabet[rand(0, $alphabetLength - 1)];
    }
    return $randomString;
}

$short = generateRandomString(6);