This commit is contained in:
2026-11-28 10:32:52 -05:00
parent 36487f9c99
commit df4861cba6
4 changed files with 238 additions and 40 deletions

View File

@ -1,3 +1,79 @@
# shortener # Micro URL Shortener
A single file URL shortener in PHP. Designed for self hosted personal use. A tiny URL shortener in a single PHP file (`index.php`). It needs no database: links are stored in plain text files.
## How it works
- `urls.txt`: one link per line, written as `<key> <url>`.
- `last.txt`: the most recently issued key. Each new key is made by incrementing it over a shuffled character set (`a`, `c`, `r`, … then `aa`, `ac`, …).
- Visiting `/<key>` sends a 301 redirect to the stored URL, or returns 404 if the key is unknown.
- Visiting `/` shows a mobile-friendly form for shortening a URL.
## Requirements
- PHP 7+ with the `mbstring` extension.
- The web server must be able to write `urls.txt` and `last.txt` in the app directory.
- Every request path must be routed to `index.php` (see below).
## Setup
1. Copy `index.php` to your web root.
2. Edit the configuration at the top of the file. At minimum, **change `$password`**.
3. Route all requests to `index.php`.
**Apache** (`.htaccess`):
```apache
RewriteEngine On
RewriteRule ^(urls|last)\.txt$ - [F]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
```
**nginx**:
```nginx
location ~ ^/(urls|last)\.txt$ { deny all; }
location / { try_files $uri /index.php?$query_string; }
```
**Local development** (PHP's built-in server, using `index.php` as the router):
```sh
php -S localhost:4000 index.php
```
> Block direct access to `urls.txt` and `last.txt` (as in the rules above). Otherwise anyone can download your whole link list.
## Configuration
| Variable | Default | Purpose |
|--------------------|----------------|----------------------------------------------------------------------|
| `$password` | `'change me!'` | Required to shorten a URL. Set to `''` to disable (not recommended). |
| `$allowed_domains` | `[]` | Domains allowed as link targets. An empty list allows any domain. |
| `$max_url_length` | `100` | Longer URLs are rejected. |
| `$charset` | (shuffled) | Characters used in keys. Don't change it once links exist. |
| `$enable_test` | `false` | Turns on the key-generation test form. |
| `$urls_file`, `$last_file` | `urls.txt`, `last.txt` | Where the data is stored. |
## API
Shorten a URL from the command line. The response is plain text:
```sh
curl --data-urlencode 'url=https://example.com/page' \
--data-urlencode 'password=your-password' \
https://your-host/
# https://your-host/c
```
| Status | Meaning |
|--------|----------------------------|
| 200 | Success; body is the short URL |
| 401 | Wrong or missing password |
| 403 | Domain not allowed |
| 422 | Invalid or overlong URL |
GET parameters work too (`/?url=...&password=...`), but they put the password in server logs and browser history, so prefer POST.
Short URLs always start with `https://` followed by the request's host.

194
index.php
View File

@ -146,41 +146,46 @@ $key = get_input('key');
$test_start = get_input('test_start'); $test_start = get_input('test_start');
$test_count = get_input('test_count'); $test_count = get_input('test_count');
// Requests from the HTML form send format=html and get the result rendered
// in the page; everything else (curl, scripts) gets the plain-text response.
$from_form = get_input('format') === 'html';
$shortened_url = null;
$error = null;
// If a URL is provided, attempt to shorten it // If a URL is provided, attempt to shorten it
if ($url) { if ($url) {
// if a password is set, check it $status = 200;
if ($password !== '' && $input_password !== $password) {
http_response_code(401); // Unauthorized
echo "Unauthorized: Incorrect password.\n";
exit;
}
// return 422 if the URL is longer than max_url_length
if (strlen($url) > $max_url_length) {
http_response_code(422); // Unprocessable Entity
echo "Invalid URL.\n";
exit;
}
// return 403 if the URL's domain is not in the allowed list
$parsed_url = parse_url($url); $parsed_url = parse_url($url);
if ($parsed_url === false || !isset($parsed_url['host']) || !test_host($parsed_url['host'])) { if ($password !== '' && $input_password !== $password) {
http_response_code(403); // if a password is set, check it
echo "Forbidden: This URL is not within the list of allowed domains.\n"; $status = 401; // Unauthorized
exit; $error = "Unauthorized: Incorrect password.";
} } elseif (strlen($url) > $max_url_length) {
// validate the URL and shorten it // reject URLs longer than max_url_length
if (filter_var($url, FILTER_VALIDATE_URL)) { $status = 422; // Unprocessable Entity
$error = "Invalid URL.";
} elseif ($parsed_url === false || !isset($parsed_url['host']) || !test_host($parsed_url['host'])) {
// reject URLs whose domain is not in the allowed list
$status = 403; // Forbidden
$error = "Forbidden: This URL is not within the list of allowed domains.";
} elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
$status = 422; // Unprocessable Entity
$error = "Invalid URL.";
} else {
// valid: shorten it
$key = add_url($url); $key = add_url($url);
$shortened_url = "https://$_SERVER[HTTP_HOST]/$key"; $shortened_url = "https://$_SERVER[HTTP_HOST]/$key";
echo "$shortened_url\n";
} else {
http_response_code(422); // Unprocessable Entity
echo "Invalid URL.\n";
} }
http_response_code($status);
if (!$from_form) {
echo ($error ?? $shortened_url) . "\n";
exit; exit;
} }
// form submission: fall through and render the result in the page
}
// If test parameters are provided, output a series of incremented keys // If test parameters are provided, output a series of incremented keys
if ($enabed_test && $test_start !== null && $test_count !== null) { if ($enable_test &&$test_start !== null && $test_count !== null) {
// validate password // validate password
if ($password !== '' && $input_password !== $password) { if ($password !== '' && $input_password !== $password) {
http_response_code(401); // Unauthorized http_response_code(401); // Unauthorized
@ -196,7 +201,7 @@ $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$key = trim($path, '/'); $key = trim($path, '/');
// If the key is valid, look up the URL and redirect // If the key is valid, look up the URL and redirect
if ($key !== '') { if ($key !== '' && !$from_form) {
$url = get_url($key); $url = get_url($key);
if ($url !== null) { if ($url !== null) {
header("Location: $url", true, 301); header("Location: $url", true, 301);
@ -215,16 +220,130 @@ if ($key !== '') {
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bagaag.com Micro URL Shortener</title> <title>Bagaag.com Micro URL Shortener</title>
<style>
*, *::before, *::after { box-sizing: border-box; }
body {
margin: 0;
padding: 1.25rem;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
font-size: 1rem;
line-height: 1.5;
color: #1f2328;
background: #f4f5f7;
}
main {
max-width: 32rem;
margin: 2rem auto;
padding: 1.5rem;
background: #fff;
border-radius: 12px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
h1 { font-size: 1.4rem; margin: 0 0 1.25rem; line-height: 1.25; }
h2 { font-size: 1.15rem; margin: 2rem 0 1rem; }
label { display: block; font-weight: 600; margin-bottom: 0.35rem; }
input[type="text"], input[type="url"], input[type="password"], input[type="number"] {
display: block;
width: 100%;
padding: 0.7rem 0.8rem;
margin-bottom: 1rem;
font: inherit;
font-size: 16px; /* 16px+ stops iOS from zooming in on focus */
border: 1px solid #c9ccd1;
border-radius: 8px;
background: #fff;
}
input:focus { outline: 2px solid #2563eb; outline-offset: 1px; border-color: #2563eb; }
input[type="submit"] {
width: 100%;
padding: 0.8rem;
font: inherit;
font-weight: 600;
color: #fff;
background: #2563eb;
border: 0;
border-radius: 8px;
cursor: pointer;
-webkit-appearance: none;
}
input[type="submit"]:hover { background: #1d4ed8; }
.result, .error { border-radius: 8px; padding: 1rem; margin-bottom: 1.25rem; }
.result { background: #ecfdf3; border: 1px solid #a6e9c1; }
.result p { margin: 0 0 0.5rem; font-weight: 600; }
.result-row { display: flex; gap: 0.5rem; }
.result-row input[type="text"] { margin: 0; flex: 1; min-width: 0; }
.result-row button {
flex: none;
padding: 0 1rem;
font: inherit;
font-weight: 600;
color: #fff;
background: #16a34a;
border: 0;
border-radius: 8px;
cursor: pointer;
}
.result a { display: inline-block; margin-top: 0.5rem; color: #15803d; word-break: break-all; }
.error { background: #fef2f2; border: 1px solid #f5b5b5; color: #b42318; font-weight: 600; }
@media (max-width: 480px) {
body { padding: 0.75rem; }
main { margin: 0.5rem auto; padding: 1.25rem; }
}
@media (prefers-color-scheme: dark) {
body { color: #e6e6e6; background: #15171a; }
main { background: #202327; box-shadow: none; }
input[type="text"], input[type="url"], input[type="password"], input[type="number"] {
color: #e6e6e6; background: #15171a; border-color: #3a3f45;
}
.result { background: #0f2a1b; border-color: #1f5a37; }
.result a { color: #6ee7a0; }
.error { background: #2d1515; border-color: #6b2a2a; color: #fca5a5; }
}
</style>
</head> </head>
<body> <body>
<main>
<h1>Bagaag.com Micro URL Shortener</h1> <h1>Bagaag.com Micro URL Shortener</h1>
<?php if ($shortened_url !== null): ?>
<div class="result">
<p>Your short URL:</p>
<div class="result-row">
<input type="text" id="short-url" readonly value="<?= htmlspecialchars($shortened_url) ?>">
<button type="button" id="copy-btn">Copy</button>
</div>
<a href="<?= htmlspecialchars($url) ?>" rel="noopener noreferrer"><?= htmlspecialchars($url) ?></a>
</div>
<script>
document.getElementById('copy-btn').addEventListener('click', function () {
var field = document.getElementById('short-url');
var btn = this;
var done = function () {
btn.textContent = 'Copied!';
setTimeout(function () { btn.textContent = 'Copy'; }, 2000);
};
if (navigator.clipboard && window.isSecureContext) {
navigator.clipboard.writeText(field.value).then(done);
} else {
field.select();
field.setSelectionRange(0, field.value.length);
if (document.execCommand('copy')) done();
}
});
</script>
<?php elseif ($error !== null): ?>
<div class="error" role="alert"><?= htmlspecialchars($error) ?></div>
<?php endif; ?>
<form method="post" action=""> <form method="post" action="">
<label for="url">Enter URL to shorten:</label><br> <input type="hidden" name="format" value="html">
<input type="text" id="url" name="url" size="50" required><br><br> <label for="url">Enter URL to shorten:</label>
<input type="url" id="url" name="url" required placeholder="https://example.com/..."
value="<?= $error !== null ? htmlspecialchars($url) : '' ?>"
autocapitalize="off" autocorrect="off" spellcheck="false">
<?php if ($password !== ''): ?> <?php if ($password !== ''): ?>
<label for="password">Enter the password:</label><br> <label for="password">Enter the password:</label>
<input type="password" id="password" name="password" size="20" required><br><br> <input type="password" id="password" name="password" autocomplete="current-password" required>
<?php endif; ?> <?php endif; ?>
<input type="submit" value="Shorten"> <input type="submit" value="Shorten">
</form> </form>
@ -232,17 +351,18 @@ if ($key !== '') {
<?php if ($enable_test): ?> <?php if ($enable_test): ?>
<h2>Test Key Generation</h2> <h2>Test Key Generation</h2>
<form method="post" action=""> <form method="post" action="">
<label for="test_start">Generate keys from:</label><br> <label for="test_start">Generate keys from:</label>
<input type="text" id="test_start" name="test_start" size="50" placeholder="Leave blank to start from beginning"><br><br> <input type="text" id="test_start" name="test_start" placeholder="Leave blank to start from beginning"
<label for="test_count">How many keys to generate:</label><br> autocapitalize="off" autocorrect="off" spellcheck="false">
<input type="text" id="test_count" name="test_count" size="10" required><br><br> <label for="test_count">How many keys to generate:</label>
<input type="number" id="test_count" name="test_count" min="1" inputmode="numeric" required>
<?php if ($password !== ''): ?> <?php if ($password !== ''): ?>
<label for="password">Enter the password:</label><br> <label for="test_password">Enter the password:</label>
<input type="password" id="password" name="password" size="20" required><br><br> <input type="password" id="test_password" name="password" autocomplete="current-password" required>
<?php endif; ?> <?php endif; ?>
<input type="submit" value="Generate"> <input type="submit" value="Generate">
</form> </form>
<?php endif; ?> <?php endif; ?>
</main>
</body> </body>
</html> </html>

1
last.txt Normal file
View File

@ -0,0 +1 @@
a

1
urls.txt Normal file
View File

@ -0,0 +1 @@
a https://cnn.com