Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorknust/49f48fbfc72b344ea4c16a4ff64a2512 to your computer and use it in GitHub Desktop.
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
// 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