Skip to content

Instantly share code, notes, and snippets.

@JanMiksovsky
Last active September 19, 2024 01:23
Show Gist options
  • Save JanMiksovsky/e748cab5d3e8f460d23ca7e51798ad27 to your computer and use it in GitHub Desktop.
Save JanMiksovsky/e748cab5d3e8f460d23ca7e51798ad27 to your computer and use it in GitHub Desktop.
Apache/PHP implementation of the JSON Keys protocol
# Enable the RewriteEngine
RewriteEngine On
# Match requests for .keys.json at any directory level, including the root
RewriteRule ^(.*)/?\.keys\.json$ /keys.php?dir=$1 [L]
<?php
// If the 'dir' parameter is omitted, return the contents of this PHP file
if (!isset($_GET['dir'])) {
$filePath = __FILE__;
if (file_exists($filePath)) {
header('Content-Type: text/plain');
echo file_get_contents($filePath);
} else {
header("HTTP/1.0 404 Not Found");
echo "File not found";
}
exit;
}
// Get the directory path from the query parameter
$directory = $_GET['dir'];
$dirPath = $_SERVER['DOCUMENT_ROOT'] . '/' . $directory;
// Ensure the directory exists
if (!is_dir($dirPath)) {
header("HTTP/1.0 404 Not Found");
echo json_encode(["error" => "Directory not found"]);
exit;
}
// Get all files and directories within the specified path
$files = scandir($dirPath);
// Collect the child names
$children = [];
foreach ($files as $file) {
// Skip the special directories "." and ".."
if ($file === '.' || $file === '..') continue;
if (is_dir($dirPath . '/' . $file)) {
// Add slash to indicate directory
$children[] = $file . '/';
} else {
// Regular file
$children[] = $file;
}
}
// Output the child array as JSON
header('Content-Type: application/json');
echo json_encode($children);
@JanMiksovsky
Copy link
Author

JanMiksovsky commented Sep 19, 2024

An Apache/PHP implementation of the simple JSON Keys protocol that lets a site route indicate the names of the resources available at that point.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment