-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom.php
More file actions
84 lines (68 loc) · 2.7 KB
/
random.php
File metadata and controls
84 lines (68 loc) · 2.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
$base_url = 'https://roadlessread.com';
// Initialize the array that will hold the URLs for random selection
$pages = [];
// Define the path to your sitemap.xml file.
// This assumes sitemap.xml is at the root of your web server's document directory.
$sitemapPath = $_SERVER['DOCUMENT_ROOT'] . '/sitemap.xml';
// List of URLs to exclude from the random selection
$exclude_urls = [
'/404',
'/random',
'/successful'
];
// Check if the sitemap file exists
if (file_exists($sitemapPath)) {
$dom = new DOMDocument();
// Load the XML file; suppress warnings for potentially malformed XML if desired
// libxml_use_internal_errors(true);
if ($dom->load($sitemapPath)) {
// libxml_clear_errors();
$xpath = new DOMXPath($dom);
// Register the sitemap namespace (standard)
$xpath->registerNamespace('s', 'http://www.sitemaps.org/schemas/sitemap/0.9');
// Query all 'loc' (location) elements
$locNodes = $xpath->query('//s:loc');
foreach ($locNodes as $locNode) {
$fullUrl = trim($locNode->nodeValue);
$relativeUrl = str_replace($base_url, '', $fullUrl);
// Special handling for the root URL
if (empty($relativeUrl) || $relativeUrl === '') {
$relativeUrl = '/';
}
// Remove trailing slash for non-root directories, if you want consistent paths
// For example, /zines/ becomes /zines, unless it's just the root /
if ($relativeUrl !== '/' && substr($relativeUrl, -1) === '/') {
$relativeUrl = rtrim($relativeUrl, '/');
}
// Add the URL to our pages array if it's not in the exclusion list
if (!in_array($relativeUrl, $exclude_urls)) {
$pages[] = $relativeUrl;
}
}
} else {
// Log error if sitemap fails to load
error_log("RANDOM PAGE ERROR: Failed to load sitemap.xml from $sitemapPath");
}
} else {
// Log error if sitemap file not found
error_log("RANDOM PAGE ERROR: Sitemap.xml not found at $sitemapPath");
// Fallback: if sitemap can't be loaded, you might want to redirect to homepage
// or a default page to prevent errors for the user.
header("Location: $base_url/");
exit;
}
// Ensure there are pages to select from after parsing and filtering
if (!empty($pages)) {
// Select Random Page
$random_page = $pages[array_rand($pages)];
// Construct Full URL
$redirect_url = $base_url . $random_page;
} else {
// If no pages were found (e.g., empty sitemap or all excluded), redirect to homepage
$redirect_url = $base_url . '/';
}
// Perform Redirect
header("Location: $redirect_url");
exit;
?>