summaryrefslogtreecommitdiff
path: root/public/read/index.php
diff options
context:
space:
mode:
authorDavid T. Sadler <davidtsadler@googlemail.com>2021-07-08 21:47:20 +0100
committerDavid T. Sadler <davidtsadler@googlemail.com>2021-07-08 21:47:20 +0100
commitea1269577fcd9d9b05f4b29ae2ad0d7c4c9a6ca2 (patch)
tree1042a5c01b93e5786a626343b19e6d5ad4275d48 /public/read/index.php
parent1155220fd5c94fa9769c55597575437581170c16 (diff)
Shorten urls
Diffstat (limited to 'public/read/index.php')
-rw-r--r--public/read/index.php33
1 files changed, 33 insertions, 0 deletions
diff --git a/public/read/index.php b/public/read/index.php
new file mode 100644
index 0000000..87857da
--- /dev/null
+++ b/public/read/index.php
@@ -0,0 +1,33 @@
+<?php declare(strict_types=1);
+
+error_reporting(E_ALL);
+
+require_once(__DIR__.'/../../includes/functions.php');
+
+$config = require_once(__DIR__.'/../../config.php');
+
+if ('GET' !== filter_input(INPUT_SERVER, 'REQUEST_METHOD')) {
+ respondAndExit(405, 'Method Not Allowed');
+}
+
+$requestedUrl = filter_input(INPUT_GET, 'url', FILTER_VALIDATE_URL);
+
+if (!$requestedUrl || strlen($requestedUrl) > $config['max_url_length']) {
+ respondAndExit(400, 'Bad Request');
+}
+
+$urls = file($config['path_to_file'], FILE_IGNORE_NEW_LINES);
+
+// Remove requested url from list if present.
+$remaingUrls = array_diff($urls, [$requestedUrl]);
+
+// Count will not have changed if requested url doesn't exist in the list.
+if (count($remaingUrls) === count($urls)) {
+ respondAndExit(404, 'Not Found');
+}
+
+if (!file_put_contents($config['path_to_file'], implode("\n", $remaingUrls))) {
+ respondAndExit(500, 'Internal Server Error');
+}
+
+respondAndExit(308, 'Permanent Redirect', ["Location: $requestedUrl"]);