@return string The timestamp of the last check or 'Never' if no checks have been made.
*/
function getLastCheckTime() {
logFile=′changedetector.log′;if(fileexists(logFile)) {
lines=file(logFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!empty(lines)) {
lastLine = end(lines);
preg_match('/\[(.*?)\]/', lastLine, matches);if(isset(matches[1])) {
return $matches[1];
}
}
}
return 'Never';
}
/**
Checks the specified URL for changes by comparing its hash with the previous hash.
@param string $url The URL to check for changes.
@return array An associative array indicating whether a change was detected and related info.
*/
function checkForChanges(url) {
// Initialize cURL session
ch = curl_init();
// Set cURL options
curl_setopt(ch,CURLOPTURL,url);
curl_setopt(ch,CURLOPTRETURNTRANSFER,true);curlch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt(ch,CURLOPTTch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
. 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
// Execute cURL request and get the response
response=curlexec(ch);
// Check for cURL errors
if (curl_errno(ch)) {
error = curl_error(ch);logMessage("cURLError:".error);
curl_close(error];
}
// Check if this is an AJAX request for checking changes
if (isset(_GET['action']) && _GET['action'] === 'check') {
header('Content-Type: application/json');
// If not an AJAX request, render the main page
$lastCheckTime = getLastCheckTime();
?>
code
<div class="hash-info" id="hashInfoContainer">
<h2>Hash Information:</h2>
<p><strong>Old Hash:</strong> <span id="oldHash">-</span></p>
<p><strong>New Hash:</strong> <span id="newHash">-</span></p>
</div>
<!-- Audio Alarm -->
<audio id="alarmAudio" loop>
<source src="alarm_1.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
<script>
// Elements
const statusContainer = document.getElementById('statusContainer');
const lastCheckSpan = document.getElementById('lastCheck');
const checkNowBtn = document.getElementById('checkNowBtn');
const loader = document.getElementById('loader');
const hashInfoContainer = document.getElementById('hashInfoContainer');
const oldHashSpan = document.getElementById('oldHash');
const newHashSpan = document.getElementById('newHash');
const alarmAudio = document.getElementById('alarmAudio');
let autoCheckInterval = null;
let alarmTimeout = null;
let isAlarmPlaying = false;
/**
* Performs an AJAX request to check for page changes.
*/
function performCheck() {
loader.style.display = 'block';
fetch('index.php?action=check')
.then(response => response.json())
.then(data => {
loader.style.display = 'none';
lastCheckSpan.textContent = data.lastCheck;
if (data.status === 'error') {
updateStatus('Error: ' + data.message, 'error');
hideHashInfo();
} else if (data.status === 'changed') {
updateStatus(data.message, 'changed');
displayHashInfo(data.hashInfo.oldHash, data.hashInfo.newHash);
triggerAlarm();
} else if (data.status === 'no-change') {
updateStatus(data.message, 'no-change');
hideHashInfo();
}
})
.catch(error => {
loader.style.display = 'none';
updateStatus('Error: ' + error.message, 'error');
});
}
/**
* Updates the status message and its styling.
*
* @param {string} message - The message to display.
* @param {string} statusClass - The CSS class for styling.
*/
function updateStatus(message, statusClass) {
statusContainer.textContent = message;
statusContainer.className = 'status ' + statusClass;
}
/**
* Displays the hash information when changes are detected.
*
* @param {string} oldHash - The previous hash value.
* @param {string} newHash - The current hash value.
*/
function displayHashInfo(oldHash, newHash) {
oldHashSpan.textContent = oldHash;
newHashSpan.textContent = newHash;
hashInfoContainer.classList.add('visible');
}
/**
* Hides the hash information section.
*/
function hideHashInfo() {
hashInfoContainer.classList.remove('visible');
oldHashSpan.textContent = '-';
newHashSpan.textContent = '-';
}
/**
* Triggers the alarm by playing the audio and stops auto-checking for 5 minutes.
*/
function triggerAlarm() {
if (!isAlarmPlaying) {
alarmAudio.currentTime = 0;
alarmAudio.play().catch(error => {
console.error("Audio playback failed:", error);
});
isAlarmPlaying = true;
// Stop the alarm after 5 minutes (300,000 milliseconds)
alarmTimeout = setTimeout(stopAlarm, 300000);
}
// Stop auto-checking for 5 minutes
stopAutoCheck();
// Resume auto-checking after 5 minutes
setTimeout(startAutoCheck, 300000);
}
/**
* Stops the alarm audio.
*/
function stopAlarm() {
alarmAudio.pause();
alarmAudio.currentTime = 0;
isAlarmPlaying = false;
console.log('Alarm stopped after 5 minutes.');
}
/**
* Starts the automatic checking interval.
*/
function startAutoCheck() {
// Immediately perform a check
performCheck();
// Set interval for every 10 seconds
autoCheckInterval = setInterval(performCheck, 10000);
console.log('Auto-checking started.');
}
/**
* Stops the automatic checking interval.
*/
function stopAutoCheck() {
if (autoCheckInterval) {
clearInterval(autoCheckInterval);
autoCheckInterval = null;
console.log('Auto-checking stopped.');
}
}
// Event listener for "Check Now" button
checkNowBtn.addEventListener('click', () => {
performCheck();
});
// Initialize auto-checking on page load
window.addEventListener('DOMContentLoaded', () => {
startAutoCheck();
});
</script>
Certainly! Below is the enhanced version of your Page Change Detector application. This updated code introduces several new features to make the tool more flexible, user-friendly, and functional, especially on mobile devices. Here's a summary of the new features:
Dynamic URL Management: Add or remove URLs directly from the interface.
Configurable Check Intervals: Set how frequently the system checks for changes.
Browser Notifications: Receive desktop notifications when changes are detected.
Responsive Design: Improved UI that works seamlessly across all devices, including mobile.
Persistent Configuration: URLs and settings are stored persistently using JSON files.
Error Handling: Enhanced error handling and logging mechanisms.
File Structure
To keep everything organized, the application uses the following files:
index.php: The main application file containing PHP, HTML, CSS, and JavaScript.
config.json: Stores the list of URLs to monitor and the check interval.
previous_hashes.json: Stores the previous hashes of the monitored URLs.
change_detector.log: Logs all activities and detected changes.
alarm.mp3: An audio file for the alarm sound (ensure you have this file in the same directory).
Note: Ensure that the server has write permissions to create and modify config.json, previous_hashes.json, and change_detector.log.
Complete index.php Code
php
<?php
// index.php
// Set the content type to HTML
header('Content-Type: text/html; charset=UTF-8');
// Error reporting for debugging (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);
// File paths
define('CONFIG_FILE', 'config.json');
define('HASH_FILE', 'previous_hashes.json');
define('LOG_FILE', 'change_detector.log');
// Initialize configuration and hash files if they don't exist
if (!file_exists(CONFIG_FILE)) {
file_put_contents(CONFIG_FILE, json_encode([
'check_interval' => 10000, // Default to 10 seconds
'urls' => []
], JSON_PRETTY_PRINT));
}
if (!file_exists(HASH_FILE)) {
file_put_contents(HASH_FILE, json_encode(new stdClass(), JSON_PRETTY_PRINT));
}
/**
* Logs messages to a specified log file with a timestamp.
*
* @param string $message The message to log.
*/
function logMessage($message) {
$timestamp = date('Y-m-d H:i:s');
file_put_contents(LOG_FILE, "[$timestamp] $message\n", FILE_APPEND);
}
/**
* Retrieves the configuration from the config file.
*
* @return array The configuration array.
*/
function getConfig() {
$config = json_decode(file_get_contents(CONFIG_FILE), true);
if ($config === null) {
$config = ['check_interval' => 10000, 'urls' => []];
}
return $config;
}
/**
* Saves the configuration to the config file.
*
* @param array $config The configuration array.
*/
function saveConfig($config) {
file_put_contents(CONFIG_FILE, json_encode($config, JSON_PRETTY_PRINT));
}
/**
* Retrieves the previous hashes from the hash file.
*
* @return array An associative array of URL => hash.
*/
function getPreviousHashes() {
$hashes = json_decode(file_get_contents(HASH_FILE), true);
if ($hashes === null) {
$hashes = [];
}
return $hashes;
}
/**
* Saves the previous hashes to the hash file.
*
* @param array $hashes An associative array of URL => hash.
*/
function savePreviousHashes($hashes) {
file_put_contents(HASH_FILE, json_encode($hashes, JSON_PRETTY_PRINT));
}
/**
* Checks the specified URL for changes by comparing its hash with the previous hash.
*
* @param string $url The URL to check for changes.
* @return array An associative array indicating whether a change was detected and related info.
*/
function checkForChanges($url) {
// Initialize cURL session
$ch = curl_init();
// Set cURL options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Set timeout to prevent hanging
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '
. 'AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36');
// Execute cURL request and get the response
$response = curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
$error = curl_error($ch);
logMessage("cURL Error for '$url': " . $error);
curl_close($ch);
return ['url' => $url, 'error' => 'Error: ' . $error];
}
// Get HTTP response code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
$error = "HTTP Error: " . $httpCode;
logMessage("HTTP Error for '$url': " . $httpCode);
curl_close($ch);
return ['url' => $url, 'error' => $error];
}
// Close cURL session
curl_close($ch);
// Generate a hash of the entire page content
$currentHash = md5($response);
// Compare with previous hash
$previousHashes = getPreviousHashes();
$previousHash = isset($previousHashes[$url]) ? $previousHashes[$url] : '';
if ($currentHash !== $previousHash) {
// Save the new hash
$previousHashes[$url] = $currentHash;
savePreviousHashes($previousHashes);
logMessage("Changes detected for '$url'. New hash: " . $currentHash);
return [
'url' => $url,
'changed' => true,
'oldHash' => $previousHash ?: 'None',
'newHash' => $currentHash
];
}
logMessage("No changes detected for '$url'.");
return ['url' => $url, 'changed' => false];
}
// Handle API actions
if (isset($_GET['action'])) {
$action = $_GET['action'];
header('Content-Type: application/json');
if ($action === 'check') {
$results = [];
$config = getConfig();
foreach ($config['urls'] as $url) {
$result = checkForChanges($url);
$results[] = $result;
}
$lastCheckTime = date('Y-m-d H:i:s');
// Prepare response
$response = [
'status' => 'completed',
'results' => $results,
'lastCheck' => $lastCheckTime
];
echo json_encode($response);
exit;
}
if ($action === 'add_url' && $_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the URL from POST data
$postData = file_get_contents('php://input');
$data = json_decode($postData, true);
$newUrl = isset($data['url']) ? trim($data['url']) : '';
if (filter_var($newUrl, FILTER_VALIDATE_URL)) {
$config = getConfig();
if (!in_array($newUrl, $config['urls'])) {
$config['urls'][] = $newUrl;
saveConfig($config);
logMessage("Added new URL to monitor: '$newUrl'.");
echo json_encode(['status' => 'success', 'message' => 'URL added successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'URL is already being monitored.']);
}
} else {
echo json_encode(['status' => 'error', 'message' => 'Invalid URL format.']);
}
exit;
}
if ($action === 'remove_url' && $_SERVER['REQUEST_METHOD'] === 'POST') {
// Get the URL from POST data
$postData = file_get_contents('php://input');
$data = json_decode($postData, true);
$removeUrl = isset($data['url']) ? trim($data['url']) : '';
$config = getConfig();
if (($key = array_search($removeUrl, $config['urls'])) !== false) {
unset($config['urls'][$key]);
$config['urls'] = array_values($config['urls']);
saveConfig($config);
// Remove the hash
$previousHashes = getPreviousHashes();
if (isset($previousHashes[$removeUrl])) {
unset($previousHashes[$removeUrl]);
savePreviousHashes($previousHashes);
}
logMessage("Removed URL from monitoring: '$removeUrl'.");
echo json_encode(['status' => 'success', 'message' => 'URL removed successfully.']);
} else {
echo json_encode(['status' => 'error', 'message' => 'URL not found in the monitoring list.']);
}
exit;
}
if ($action === 'get_config') {
$config = getConfig();
$lastCheckTime = file_exists(LOG_FILE) ? getLastLogCheckTime() : 'Never';
// Get statuses
$statuses = [];
$previousHashes = getPreviousHashes();
foreach ($config['urls'] as $url) {
$statuses[] = [
'url' => $url,
'lastHash' => isset($previousHashes[$url]) ? substr($previousHashes[$url], 0, 8) . '…' : 'None'
];
}
$response = [
'check_interval' => $config['check_interval'],
'urls' => $config['urls'],
'statuses' => $statuses,
'lastCheck' => $lastCheckTime
];
echo json_encode($response);
exit;
}
}
// Function to get the last check time from the log file
function getLastLogCheckTime() {
if (file_exists(LOG_FILE)) {
$lines = file($LOG_FILE, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!empty($lines)) {
$lastLine = end($lines);
preg_match('/\[(.*?)\]/', $lastLine, $matches);
if (isset($matches[1])) {
return $matches[1];
}
}
}
return 'Never';
}
// If not an API request, render the main page
$lastCheckTime = getLastLogCheckTime();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page Change Detector</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;600&display=swap" rel="stylesheet">
<style>
/* Reset and basic styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Poppins', sans-serif;
background: linear-gradient(135deg, #ece9e6, #ffffff);
color: #333;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
padding: 20px;
}
/* Container styling */
.container {
background-color: #ffffffdd;
backdrop-filter: blur(10px);
border-radius: 15px;
padding: 30px 40px;
box-shadow: 0 20px 40px rgba(0,0,0,0.1);
max-width: 900px;
width: 100%;
text-align: center;
position: relative;
}
h1 {
margin-bottom: 20px;
font-size: 32px;
color: #2c3e50;
}
/* Status message styling */
.status-container {
margin: 20px 0;
text-align: left;
}
.status-item {
padding: 15px 20px;
border-radius: 10px;
background-color: #f1f2f6;
border: 1px solid #dcdde1;
margin-bottom: 10px;
position: relative;
}
.status-item.changed {
background-color: #e74c3c;
color: #ffffff;
}
.status-item.no-change {
background-color: #2ecc71;
color: #ffffff;
}
.status-item.error {
background-color: #f39c12;
color: #ffffff;
}
.status-item .url {
font-weight: 600;
}
.status-item .hash-info {
font-family: monospace;
margin-top: 5px;
}
.status-item .remove-btn {
position: absolute;
top: 15px;
right: 20px;
background-color: #e74c3c;
border: none;
color: #fff;
padding: 5px 10px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s;
}
.status-item .remove-btn:hover {
background-color: #c0392b;
}
/* Last check time styling */
.last-check {
font-size: 14px;
color: #7f8c8d;
margin-bottom: 30px;
}
/* Add URL form styling */
.add-url-form {
display: flex;
justify-content: center;
margin-bottom: 20px;
flex-wrap: wrap;
}
.add-url-form input {
padding: 10px;
font-size: 16px;
width: 60%;
border: 1px solid #dcdde1;
border-radius: 5px;
margin-right: 10px;
min-width: 200px;
}
.add-url-form button {
padding: 10px 20px;
font-size: 16px;
color: #ffffff;
background-color: #3498db;
border: none;
border-radius: 50px;
cursor: pointer;
transition: background-color 0.3s;
margin-top: 10px;
}
.add-url-form button:hover {
background-color: #2980b9;
}
/* Button styling */
.btn {
padding: 12px 30px;
font-size: 16px;
color: #ffffff;
background-color: #3498db;
border: none;
border-radius: 50px;
cursor: pointer;
transition: background-color 0.3s, transform 0.2s;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
margin-top: 10px;
}
.btn:hover {
background-color: #2980b9;
transform: translateY(-2px);
}
/* Loader styling */
.loader {
border: 6px solid #f3f3f3;
border-top: 6px solid #3498db;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 1s linear infinite;
display: none;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Responsive design */
@media (max-width: 768px) {
.container {
padding: 30px 20px;
}
h1 {
font-size: 28px;
}
.add-url-form input {
width: 100%;
margin-right: 0;
margin-bottom: 10px;
}
.add-url-form button {
width: 100%;
}
}
@media (max-width: 480px) {
.container {
padding: 20px 15px;
}
h1 {
font-size: 24px;
}
.add-url-form input {
font-size: 14px;
}
.add-url-form button {
font-size: 14px;
}
.btn {
padding: 10px 20px;
font-size: 14px;
}
.status-item {
padding: 10px 15px;
}
.status-item .remove-btn {
top: 10px;
right: 15px;
padding: 4px 8px;
}
}
</style>
</head>
<body>
<div class="container">
<h1>Page Change Detector</h1>
<!-- Add URL Form -->
<div class="add-url-form">
<input type="url" id="newUrlInput" placeholder="Enter URL to monitor (e.g., https://example.com)" required>
<button id="addUrlBtn">Add URL</button>
</div>
<!-- Status Messages -->
<div class="status-container" id="statusContainer">
<!-- Dynamic status items will be appended here -->
</div>
<!-- Last Check Time -->
<div class="last-check">
Last checked: <span id="lastCheck">Never</span>
</div>
<!-- Check Now Button -->
<button class="btn" id="checkNowBtn">Check Now</button>
<!-- Loader -->
<div class="loader" id="loader"></div>
<!-- Audio Alarm -->
<audio id="alarmAudio" loop>
<source src="alarm.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</div>
<script>
// Elements
const statusContainer = document.getElementById('statusContainer');
const lastCheckSpan = document.getElementById('lastCheck');
const checkNowBtn = document.getElementById('checkNowBtn');
const loader = document.getElementById('loader');
const addUrlBtn = document.getElementById('addUrlBtn');
const newUrlInput = document.getElementById('newUrlInput');
const alarmAudio = document.getElementById('alarmAudio');
let autoCheckInterval = null;
let alarmTimeout = null;
let isAlarmPlaying = false;
let checkInterval = 10000; // Default to 10 seconds
/**
* Fetches the configuration and updates the UI.
*/
function fetchConfig() {
fetch('index.php?action=get_config')
.then(response => response.json())
.then(data => {
updateUI(data);
})
.catch(error => {
console.error('Error fetching config:', error);
});
}
/**
* Updates the UI based on the configuration data.
*
* @param {object} data - The configuration data.
*/
function updateUI(data) {
// Update last check time
lastCheckSpan.textContent = data.lastCheck;
// Clear existing statuses
statusContainer.innerHTML = '';
// Update check interval
checkInterval = data.check_interval;
// Populate status items
data.statuses.forEach(status => {
const statusItem = document.createElement('div');
statusItem.classList.add('status-item');
// Determine status class
// This example assumes that if a hash has changed, it's marked as 'changed'
// You'll need to adjust based on your backend's response structure
// For simplicity, we mark all as 'no-change' here
// You might want to enhance the backend to send status per URL
statusItem.classList.add('no-change');
statusItem.innerHTML = `
<span class="url">${status.url}</span>
<div class="hash-info">Last Hash: ${status.lastHash}</div>
<button class="remove-btn" data-url="${status.url}">Remove</button>
`;
statusContainer.appendChild(statusItem);
});
}
/**
* Performs an AJAX request to check for page changes.
*/
function performCheck() {
loader.style.display = 'block';
fetch('index.php?action=check')
.then(response => response.json())
.then(data => {
loader.style.display = 'none';
lastCheckSpan.textContent = data.lastCheck;
data.results.forEach(result => {
updateStatus(result);
});
if (data.results.some(r => r.changed === true)) {
triggerAlarm();
showNotification('Page Change Detected', 'One or more monitored pages have changed.');
}
})
.catch(error => {
loader.style.display = 'none';
console.error('Error during check:', error);
});
}
/**
* Updates the status message and its styling for a specific URL.
*
* @param {object} result - The result object from the check.
*/
function updateStatus(result) {
// Find the corresponding status item
const statusItems = document.querySelectorAll('.status-item');
statusItems.forEach(item => {
const urlSpan = item.querySelector('.url');
if (urlSpan.textContent === result.url) {
if (result.error) {
item.classList.remove('no-change', 'changed');
item.classList.add('error');
item.querySelector('.hash-info').textContent = `Error: ${result.error}`;
} else if (result.changed) {
item.classList.remove('no-change', 'error');
item.classList.add('changed');
item.querySelector('.hash-info').textContent = `Old Hash: ${result.oldHash} | New Hash: ${result.newHash}`;
} else {
item.classList.remove('changed', 'error');
item.classList.add('no-change');
item.querySelector('.hash-info').textContent = `Last Hash: ${result.newHash}`;
}
}
});
}
/**
* Triggers the alarm by playing the audio and stops auto-checking for 5 minutes.
*/
function triggerAlarm() {
if (!isAlarmPlaying) {
alarmAudio.currentTime = 0;
alarmAudio.play().catch(error => {
console.error("Audio playback failed:", error);
});
isAlarmPlaying = true;
// Stop the alarm after 5 minutes (300,000 milliseconds)
alarmTimeout = setTimeout(stopAlarm, 300000);
}
// Stop auto-checking for 5 minutes
stopAutoCheck();
// Resume auto-checking after 5 minutes
setTimeout(startAutoCheck, 300000);
}
/**
* Stops the alarm audio.
*/
function stopAlarm() {
alarmAudio.pause();
alarmAudio.currentTime = 0;
isAlarmPlaying = false;
console.log('Alarm stopped after 5 minutes.');
}
/**
* Starts the automatic checking interval.
*/
function startAutoCheck() {
// Immediately perform a check
performCheck();
// Set interval based on checkInterval
autoCheckInterval = setInterval(performCheck, checkInterval);
console.log('Auto-checking started.');
}
/**
* Stops the automatic checking interval.
*/
function stopAutoCheck() {
if (autoCheckInterval) {
clearInterval(autoCheckInterval);
autoCheckInterval = null;
console.log('Auto-checking stopped.');
}
}
/**
* Sends a browser notification.
*
* @param {string} title - The notification title.
* @param {string} body - The notification body.
*/
function showNotification(title, body) {
if (Notification.permission === 'granted') {
new Notification(title, { body: body });
}
}
/**
* Requests notification permission from the user.
*/
function requestNotificationPermission() {
if ('Notification' in window) {
if (Notification.permission === 'default') {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
console.log('Notification permission granted.');
}
});
}
}
}
/**
* Adds a new URL to monitor.
*
* @param {string} url - The URL to add.
*/
function addUrl(url) {
fetch('index.php?action=add_url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ url: url })
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
fetchConfig();
performCheck();
} else {
alert(data.message);
}
})
.catch(error => {
console.error('Error adding URL:', error);
});
}
/**
* Removes a URL from monitoring.
*
* @param {string} url - The URL to remove.
*/
function removeUrl(url) {
fetch('index.php?action=remove_url', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ url: url })
})
.then(response => response.json())
.then(data => {
if (data.status === 'success') {
fetchConfig();
} else {
alert(data.message);
}
})
.catch(error => {
console.error('Error removing URL:', error);
});
}
// Event listener for "Check Now" button
checkNowBtn.addEventListener('click', () => {
performCheck();
});
// Event listener for "Add URL" button
addUrlBtn.addEventListener('click', () => {
const newUrl = newUrlInput.value.trim();
if (newUrl === '') {
alert('Please enter a URL.');
return;
}
addUrl(newUrl);
newUrlInput.value = '';
});
// Event delegation for "Remove" buttons
statusContainer.addEventListener('click', (e) => {
if (e.target.classList.contains('remove-btn')) {
const url = e.target.getAttribute('data-url');
if (confirm(`Are you sure you want to stop monitoring "${url}"?`)) {
removeUrl(url);
}
}
});
// Initialize notification permission and fetch initial config
window.addEventListener('DOMContentLoaded', () => {
requestNotificationPermission();
fetchConfig();
startAutoCheck();
});
</script>
</body>
</html>
Explanation of the Enhancements
Multiple URL Monitoring:
The application can now monitor multiple URLs. Users can add or remove URLs through the interface.
The config.json file stores the list of URLs and the check interval.
Dynamic URL Management:
Add URL: Users can enter a URL in the input field and click "Add URL" to start monitoring it.
Remove URL: Each monitored URL has a "Remove" button, allowing users to stop monitoring that particular URL.
Configurable Check Intervals:
The check interval is set in the config.json file. For simplicity, it's set to 10 seconds by default (10000 milliseconds). You can modify this value directly in config.json or extend the UI to allow dynamic changes.
Browser Notifications:
The application requests permission to send browser notifications.
When changes are detected on any monitored URL, a desktop notification is displayed.
Ensure that your browser allows notifications from the site where this application is hosted.
Responsive Design:
The CSS has been enhanced to ensure the application is mobile-friendly.
Elements adjust their layout based on the screen size, ensuring usability across devices.
Persistent Configuration:
URLs and their previous hashes are stored in config.json and previous_hashes.json, respectively.
These configurations persist even after the server restarts or if the application is closed and reopened.
Error Handling:
Enhanced error handling in both PHP and JavaScript ensures that users are informed of any issues, such as invalid URLs or network errors.
All activities, including errors and detected changes, are logged in change_detector.log for auditing and debugging purposes.
Additional Recommendations
Alarm Sound:
Ensure that you have an audio file named alarm.mp3 in the same directory as index.php. This sound plays when changes are detected. You can use any preferred alarm sound.
Security Considerations:
This application does not implement authentication. If deployed in a production environment, consider adding authentication mechanisms to prevent unauthorized access.
Validate and sanitize all user inputs to prevent security vulnerabilities such as injection attacks.
Advanced Features:
Configurable Check Interval via UI: You can extend the UI to allow users to set the check interval dynamically.
Detailed Change Reports: Instead of just hashing, you can implement more detailed change detection mechanisms, such as tracking specific elements or using diff algorithms.
Email Notifications: In addition to browser notifications, you can integrate email notifications for critical changes.
Server-Side Enhancements:
Cron Jobs: For more efficient monitoring, consider setting up server-side cron jobs to perform checks at regular intervals instead of relying solely on client-side checks.
Database Integration: For scalability, especially when monitoring a large number of URLs, integrating a database can be beneficial.
Conclusion
This enhanced Page Change Detector provides a robust and flexible solution for monitoring multiple web pages for changes. With its user-friendly interface, persistent configurations, and responsive design, it's well-suited for both desktop and mobile users. Feel free to further customize and expand its features based on your specific requirements.