Slug generator
Owner: coffeeman
Created: 2026-05-01 22:46:46
Size: 0.94 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
/**
* Generates a URL-safe, cryptographically secure random string.
* Ideal for routing, password resets, or secure text-sharing links (e.g., uploadtext.app/aBc12XyZ).
*
* @param int $length The desired length of the slug
* @return string
*/
function generateSecureSlug(int $length = 8): string
{
// Calculate how many random bytes we need
$bytesNeeded = (int) ceil($length * 0.75);
$randomBytes = random_bytes($bytesNeeded);
// Encode to Base64, then make it URL-safe by replacing + and / with - and _
$base64 = base64_encode($randomBytes);
$urlSafeString = strtr($base64, '+/', '-_');
// Strip padding and trim to the exact requested length
$slug = rtrim($urlSafeString, '=');
return substr($slug, 0, $length);
}
// Usage Example:
// echo generateSecureSlug(6); // Outputs something like: "K9x_2A"
// echo generateSecureSlug(12); // Outputs something like: "pM3v-qL8zY1x"