= 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'); // The auth cookie holds an HMAC of the password, never the password itself. // Changing $password invalidates every cookie already issued. function auth_token() { global $password; return hash_hmac('sha256', 'shortener-auth', $password); } // True if the request carries a valid auth cookie function has_auth_cookie() { global $password, $auth_cookie; return $password !== '' && isset($_COOKIE[$auth_cookie]) && is_string($_COOKIE[$auth_cookie]) && hash_equals(auth_token(), $_COOKIE[$auth_cookie]); } // Sets the auth cookie, or clears it when $value is '' function set_auth_cookie($value) { global $auth_cookie, $auth_cookie_days; setcookie($auth_cookie, $value, [ 'expires' => $value === '' ? time() - 3600 : time() + $auth_cookie_days * 86400, 'path' => '/', 'secure' => !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off', 'httponly' => true, 'samesite' => 'Lax', ]); } // Checks the password or auth cookie. On a correct password with the // "remember" box ticked, sets the cookie. The cookie only counts for POST, // so a link like /?url=... on another site can't create short links with // a visitor's cookie. function is_authorized() { global $password, $input_password, $has_cookie; if ($password === '') { return true; } if (is_string($input_password) && hash_equals($password, $input_password)) { if (get_input('remember') === '1') { set_auth_cookie(auth_token()); $has_cookie = true; } return true; } return $has_cookie && $_SERVER['REQUEST_METHOD'] === 'POST'; } $has_cookie = has_auth_cookie(); // Log out: clear the cookie, then redirect so a refresh doesn't resubmit. // POST only, so another site can't log a visitor out with a plain link. if ($_SERVER['REQUEST_METHOD'] === 'POST' && get_input('logout') !== null) { set_auth_cookie(''); header('Location: /', true, 303); exit; } // 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 (!is_authorized()) { // if a password is set, check it (or the auth cookie) $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 (or the auth cookie) if (!is_authorized()) { 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 ?>