369 lines
13 KiB
PHP
369 lines
13 KiB
PHP
<?php
|
|
// Simple URL shortener in a single PHP file
|
|
// by bagaag.com
|
|
|
|
// Configuration
|
|
$last_file = 'last.txt'; // file to store the last incremented key
|
|
$urls_file = 'urls.txt'; // file to store the URLs with their keys
|
|
$charset = 'acr8mqbs7di4tuh6e9fjv2gwx0nlk5poy1z3'; // unique set of characters for generating keys
|
|
$max_url_length = 100; // urls longer than this are considered nefarious
|
|
$allowed_domains = []; // list of allowed domains for URL shortening
|
|
$password = 'change me!'; // password to shorten a URL, leave empty to disable password protection
|
|
$enable_test = false; // enable the test function to output a series of incremented keys
|
|
|
|
// Returns the contents of $last_file, or empty string if the file does not exist
|
|
function get_last() {
|
|
global $last_file;
|
|
if (file_exists($last_file)) {
|
|
return trim(file_get_contents($last_file));
|
|
}
|
|
return '';
|
|
}
|
|
|
|
// Writes to $last_file
|
|
function set_last($s) {
|
|
global $last_file;
|
|
file_put_contents($last_file, $s);
|
|
}
|
|
|
|
// Provides the next key by incrementing the previous key.
|
|
// Start with empty string and then feed the return value
|
|
// back into this function to get the next key, and repeat.
|
|
function increment_string($s) {
|
|
global $charset;
|
|
// convert the charset to an array of characters
|
|
$chars = str_to_chars($charset);
|
|
// if the string is empty, return the first character
|
|
if ($s === '') {
|
|
return $chars[0];
|
|
}
|
|
// convert the input string to an array of characters
|
|
$string = str_to_chars($s);
|
|
// iterate over the input string characters from end to beginning
|
|
for ($index = count($string) - 1; $index >= 0; $index--) {
|
|
// find and validate the position of the character in the charset
|
|
$char = $string[$index];
|
|
$pos = array_search($char, $chars);
|
|
if ($pos === false) {
|
|
return "Character not in set: $char";
|
|
}
|
|
// if the character is not the last in the charset, increment it and break
|
|
if ($pos < count($chars) - 1) {
|
|
$string[$index] = $chars[$pos + 1];
|
|
break;
|
|
}
|
|
// character is the last in the charset; wrap around to the first character
|
|
$string[$index] = $chars[0];
|
|
// if we are at the beginning of the string, prepend the first character and break
|
|
if ($index === 0) {
|
|
array_unshift($string, $chars[0]);
|
|
break;
|
|
}
|
|
}
|
|
return join('', $string);
|
|
}
|
|
|
|
// Splits a string into an array of characters
|
|
function str_to_chars($str, $l = 0) {
|
|
if ($l > 0) {
|
|
$ret = array();
|
|
$len = mb_strlen($str, "UTF-8");
|
|
for ($i = 0; $i < $len; $i += $l) {
|
|
$ret[] = mb_substr($str, $i, $l, "UTF-8");
|
|
}
|
|
return $ret;
|
|
}
|
|
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
|
|
}
|
|
|
|
// Reads the last key, increments it, saves it, and returns it
|
|
function next_key() {
|
|
$last = get_last();
|
|
$next = increment_string($last);
|
|
set_last($next);
|
|
return $next;
|
|
}
|
|
|
|
// Adds a URL to urls.txt and returns the generated key
|
|
function add_url($url) {
|
|
global $urls_file;
|
|
$key = next_key();
|
|
// append the key and url to urls.txt
|
|
file_put_contents($urls_file, $key . ' ' . $url . "\n", FILE_APPEND);
|
|
return $key;
|
|
}
|
|
|
|
// Looks up a key in urls.txt and returns the corresponding URL, or null if not found
|
|
function get_url($key) {
|
|
global $urls_file;
|
|
$lines = file($urls_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
|
|
foreach ($lines as $line) {
|
|
list($k, $url) = explode(' ', $line, 2);
|
|
if ($k === $key) {
|
|
return $url;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// Test function to print a series of incremented keys
|
|
// Usage: output_keys('', 100);
|
|
function output_keys($key, $count) {
|
|
header('Content-Type: text/plain');
|
|
for ($i = 0; $i < $count; $i++) {
|
|
$key = increment_string($key);
|
|
// set content type to plain text
|
|
print($key . "\n");
|
|
}
|
|
}
|
|
|
|
// Get input either from a GET or POST request
|
|
function get_input($name) {
|
|
if (isset($_POST[$name])) {
|
|
return $_POST[$name];
|
|
} elseif (isset($_GET[$name])) {
|
|
return $_GET[$name];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
// Test if a host is in the allowed domains list
|
|
function test_host($host) {
|
|
global $allowed_domains;
|
|
if (empty($allowed_domains)) {
|
|
return true; // if the list is empty, allow all domains
|
|
}
|
|
return in_array($host, $allowed_domains);
|
|
}
|
|
|
|
|
|
/* HTTP Request Handling */
|
|
|
|
// read input parameters
|
|
$url = get_input('url');
|
|
$input_password = get_input('password');
|
|
$key = get_input('key');
|
|
$test_start = get_input('test_start');
|
|
$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 ($url) {
|
|
$status = 200;
|
|
$parsed_url = parse_url($url);
|
|
if ($password !== '' && $input_password !== $password) {
|
|
// if a password is set, check it
|
|
$status = 401; // Unauthorized
|
|
$error = "Unauthorized: Incorrect password.";
|
|
} elseif (strlen($url) > $max_url_length) {
|
|
// reject URLs longer than max_url_length
|
|
$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);
|
|
$shortened_url = "https://$_SERVER[HTTP_HOST]/$key";
|
|
}
|
|
http_response_code($status);
|
|
if (!$from_form) {
|
|
echo ($error ?? $shortened_url) . "\n";
|
|
exit;
|
|
}
|
|
// form submission: fall through and render the result in the page
|
|
}
|
|
|
|
// If test parameters are provided, output a series of incremented keys
|
|
if ($enable_test &&$test_start !== null && $test_count !== null) {
|
|
// validate password
|
|
if ($password !== '' && $input_password !== $password) {
|
|
http_response_code(401); // Unauthorized
|
|
echo "Unauthorized: Incorrect password.\n";
|
|
exit;
|
|
}
|
|
output_keys($test_start, (int)$test_count);
|
|
exit;
|
|
}
|
|
|
|
// Otherwise, assume the request URI is a key to look up
|
|
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
|
|
$key = trim($path, '/');
|
|
|
|
// If the key is valid, look up the URL and redirect
|
|
if ($key !== '' && !$from_form) {
|
|
$url = get_url($key);
|
|
if ($url !== null) {
|
|
header("Location: $url", true, 301);
|
|
exit;
|
|
} else {
|
|
http_response_code(404);
|
|
echo "Not Found.\n";
|
|
exit;
|
|
}
|
|
}
|
|
// If no key or url is provided, show a simple HTML form to submit a URL
|
|
?>
|
|
<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="UTF-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
<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>
|
|
<body>
|
|
<main>
|
|
<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="">
|
|
<input type="hidden" name="format" value="html">
|
|
<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 !== ''): ?>
|
|
<label for="password">Enter the password:</label>
|
|
<input type="password" id="password" name="password" autocomplete="current-password" required>
|
|
<?php endif; ?>
|
|
<input type="submit" value="Shorten">
|
|
</form>
|
|
|
|
<?php if ($enable_test): ?>
|
|
<h2>Test Key Generation</h2>
|
|
<form method="post" action="">
|
|
<label for="test_start">Generate keys from:</label>
|
|
<input type="text" id="test_start" name="test_start" placeholder="Leave blank to start from beginning"
|
|
autocapitalize="off" autocorrect="off" spellcheck="false">
|
|
<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 !== ''): ?>
|
|
<label for="test_password">Enter the password:</label>
|
|
<input type="password" id="test_password" name="password" autocomplete="current-password" required>
|
|
<?php endif; ?>
|
|
<input type="submit" value="Generate">
|
|
</form>
|
|
<?php endif; ?>
|
|
</main>
|
|
</body>
|
|
</html>
|