Created
May 15, 2025 15:31
-
-
Save keevitaja/27af7833cdf9bf64d5f9877922d1e864 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| <?php | |
| /** | |
| * .htaccess file: | |
| * | |
| * RewriteEngine On | |
| * RewriteBase / | |
| * | |
| * # Skip existing files and directories | |
| * RewriteCond %{REQUEST_FILENAME} !-f | |
| * RewriteCond %{REQUEST_FILENAME} !-d | |
| * # Placeholder for shortened URLs | |
| * # shorten.php will append rules below this line | |
| * # ------------------ SHORT LINKS BELOW ------------------ | |
| */ | |
| // Configuration | |
| $htaccessFile = '.htaccess'; | |
| $slugLength = 5; | |
| // Create random slug | |
| function generateSlug($length = 5): string { | |
| return substr(str_shuffle(str_repeat('abcdefghijklmnopqrstuvwxyz', $length)), 0, $length); | |
| } | |
| // Check if slug already exists in .htaccess | |
| function slugExists($slug, $file): bool { | |
| if (!file_exists($file)) return false; | |
| $contents = file_get_contents($file); | |
| return str_contains($contents, "RewriteRule ^$slug\\b"); | |
| } | |
| // Store redirect rule in .htaccess | |
| function saveToHtaccess($slug, $url, $file): bool { | |
| $rule = "RewriteRule ^$slug\$ $url [R=302,L]" . PHP_EOL; | |
| return file_put_contents($file, $rule, FILE_APPEND | LOCK_EX) !== false; | |
| } | |
| // Handle form submission | |
| if ($_SERVER['REQUEST_METHOD'] === 'POST') { | |
| $url = trim($_POST['url'] ?? ''); | |
| if (!filter_var($url, FILTER_VALIDATE_URL)) { | |
| die("Invalid URL."); | |
| } | |
| do { | |
| $slug = generateSlug($slugLength); | |
| } while (slugExists($slug, $htaccessFile)); | |
| if (saveToHtaccess($slug, $url, $htaccessFile)) { | |
| echo "Short URL created: <a href='/$slug'>/$slug</a>"; | |
| } else { | |
| echo "Failed to save to .htaccess."; | |
| } | |
| exit; | |
| } | |
| ?> | |
| <form method="post"> | |
| <input type="url" name="url" required placeholder="Enter full URL"> | |
| <button type="submit">Shorten</button> | |
| </form> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment