diff options
| -rw-r--r-- | .gitignore | 1 | ||||
| -rw-r--r-- | public/bookmarks/index.php | 47 | 
2 files changed, 48 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4f4773f --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +config.php diff --git a/public/bookmarks/index.php b/public/bookmarks/index.php new file mode 100644 index 0000000..8ecfe24 --- /dev/null +++ b/public/bookmarks/index.php @@ -0,0 +1,47 @@ +<?php declare(strict_types=1); + +error_reporting(E_ALL); + +$config = require_once('../../config.php'); + +if ('POST' !== ($_SERVER['REQUEST_METHOD'] ?? null)) { +    respondAndExit([405 => 'Method Not Allowed']); +} + +if ('Bearer '.$config['bearer_token'] !== ($_SERVER['HTTP_AUTHORIZATION'] ?? null)) { +    respondAndExit([ +        401 => 'Unauthorized', +        0   => 'WWW-Authenticate: Bearer realm="Bookmarks"', +    ]); +} + +if ('application/x-www-form-urlencoded' !== ($_SERVER['CONTENT_TYPE'] ?? null)) { +    respondAndExit([415 => 'Unsupported Media Type']); +} + +$url = filter_input(INPUT_POST, 'url', FILTER_VALIDATE_URL); + +if (!$url || !strlen($url) === 0 || strlen($url) > $config['max_url_length']) { +    respondAndExit([400 => 'Bad Request']); +} + +if (!file_put_contents($config['path_to_file'], "$url\n", FILE_APPEND)) { +    respondAndExit([500 => 'Internal Server Error']); +} + +respondAndExit([201 => 'Created']); + +function respondAndExit(array $headers): void +{ +    foreach ($headers as $responseCode => $header) { +        if ($responseCode) { +            header($header, false, $responseCode); +        } else { +            header($header); +        } +    } + +    header('Content-type: text/plain; charset=UTF-8'); + +    exit(); +}  | 
