-
-
Save victorknust/49f48fbfc72b344ea4c16a4ff64a2512 to your computer and use it in GitHub Desktop.
Generate 6 Character Random Bit.ly like ID for a URL with PHP and MySQL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Set number of shortcodes to generate | |
$shortcodes = 10000000; | |
// Loop through and create unique shortcodes | |
while ($shortcodes) { | |
$shortcode = generateShortcode(); | |
$checkSQL = "SELECT shortcode FROM shortcodes WHERE shortcode = '" . $shortcode . "'"; | |
$checkResult = $mysqli->query($checkSQL); | |
// If doesn't exist, insert into database | |
if ($checkResult->num_rows == 0) { | |
$sql = "INSERT IGNORE INTO shortcodes (shortcode) VALUES ('" . $shortcode . "')"; | |
$mysqli->query($sql); | |
echo "Inserted Shortcode: " . $shortcode . "\r\n"; | |
$shortcodes--; | |
} | |
} | |
// Function to generate shortcode | |
function generateShortcode() { | |
$shortcode = substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) . | |
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) . | |
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) . | |
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) . | |
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1) . | |
substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', rand(0,61), 1); | |
return $shortcode; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment