【问题标题】:PHP Random Name instead of sequencePHP随机名称而不是序列
【发布时间】:2018-05-22 01:18:01
【问题描述】:

我有一个基本的 URL 缩短脚本,但我遇到了问题。每次我输入一个新的 url 来缩短脚本时,只需将下一个字母添加到数据库中(即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`');
    }
}
}

?>

【问题讨论】:

标签: php


【解决方案1】:

试试这样的:

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);

【讨论】:

    猜你喜欢
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2011-07-22
    • 2013-06-12
    • 2011-06-19
    • 2018-10-05
    • 1970-01-01
    相关资源
    最近更新 更多