Here's the complete, improved PHP script that detects changes on the specified webpage every 10 seconds. If a change is detected, it plays an audio alarm (alarm_1.mp3) in a loop for 5 minutes. The interface is designed for clarity and responsiveness.
Features Implemented:
- Automatic Checking: The page automatically checks for changes every 10 seconds without requiring manual refreshes.
- Change Detection: Utilizes hashing to detect changes in the target webpage.
- Audio Alarm: Plays
alarm_1.mp3 for 5 minutes if a change is detected.
- Logging: Logs all activities and errors to
change_detector.log.
- Responsive Design: Clean and modern UI using CSS.
Complete Code: index.php
<?php
// index.php
// Error reporting for debugging (disable in production)
error_reporting(E_ALL);
ini_set('display_errors', 1);
/**
* Logs messages to a specified log file with a timestamp.
*
* @param string $message The message to log.
*/
function logMessage($message) {
$logFile = 'change_detector.log';
$timestamp = date('Y-m-d H:i:s');
file_put_contents($logFile, "[$timestamp] $message\n", FILE_APPEND);
}
/**
* Retrieves the last check time from the log file.
*
* @return string The timestamp of the last check or 'Never' if no checks have been made.
*/
function getLastCheckTime() {
$logFile = 'change_detector.log';
if (file_exists($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, 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: " . $error);
curl_close($ch);
return ['error' => 'Error: ' . $error];
}
// Get HTTP response code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode !== 200) {
$error = "HTTP Error: " . $httpCode;
logMessage($error);
curl_close($ch);
return ['error' => $error];
}
// Close cURL session
curl_close($ch);
// Generate a hash of the entire page content
$currentHash = md5($response);
// Compare with previous hash
$previousHash = '';
if (file_exists('previous_hash.txt')) {
$previousHash = file_get_contents('previous_hash.txt');
}
if ($currentHash !== $previousHash) {
// Save the new hash
file_put_contents('previous_hash.txt', $currentHash);
logMessage("Changes detected. New hash: " . $currentHash);
return [
'changed' => true,
'oldHash' => $previousHash,
'newHash' => $currentHash
];
}
logMessage("No changes detected");
return ['changed' => false];
}
// Define the URL to monitor
$url = 'https://longevacare.com/the-longeva-concept/';
// Initialize variables
$lastCheckTime = getLastCheckTime();
$changeStatus = 'No changes detected';
$hashInfo = '';
$changesDetected = false;
$playAlarm = false;
// Handle change checking
$result = checkForChanges($url);
$lastCheckTime = date('Y-m-d H:i:s');
if (isset($result['error'])) {
$changeStatus = $result['error'];
logMessage("Error occurred: " . $result['error']);
} elseif ($result['changed']) {
$changeStatus = 'Changes detected!';
$hashInfo = "Old Hash: " . substr($result['oldHash'], 0, 8) . "…<br>New Hash: " . substr($result['newHash'], 0, 8) . "…";
logMessage("Changes detected on the page");
$changesDetected = true;
$playAlarm = true;
} else {
$changeStatus = 'No changes detected';
logMessage("No changes detected on the page");
$changesDetected = false;
}
?>
<!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 http-equiv="refresh" content="10"> <!-- Auto-refresh every 10 seconds -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Longeva Care Page Change Detector</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
<style>
/* Reset and basic styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Roboto', sans-serif;
background-color: #f5f6fa;
color: #2c3e50;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
/* Container styling */
.container {
background-color: #ffffff;
border-radius: 10px;
padding: 40px;
box-shadow: 0 8px 16px rgba(0,0,0,0.1);
max-width: 600px;
width: 100%;
text-align: center;
}
h1 {
margin-bottom: 20px;
font-size: 28px;
color: #34495e;
}
/* Status message styling */
.status {
font-size: 22px;
font-weight: bold;
margin: 20px 0;
padding: 15px;
border-radius: 8px;
transition: background-color 0.3s, color 0.3s;
}
.status.no-changes {
background-color: #2ecc71;
color: #ffffff;
}
.status.changes-detected {
background-color: #e74c3c;
color: #ffffff;
}
.status.error {
background-color: #f39c12;
color: #ffffff;
}
/* Last check time styling */
.last-check {
font-size: 14px;
color: #7f8c8d;
margin-bottom: 30px;
}
/* Hash information styling */
.hash-info {
background-color: #ecf0f1;
border: 1px solid #bdc3c7;
padding: 20px;
border-radius: 8px;
font-family: monospace;
margin-top: 20px;
display: none;
}
.hash-info.visible {
display: block;
}
/* Button styling */
.btn-refresh {
padding: 12px 24px;
font-size: 16px;
color: #ffffff;
background-color: #3498db;
border: none;
border-radius: 6px;
cursor: pointer;
transition: background-color 0.3s;
}
.btn-refresh:hover {
background-color: #2980b9;
}
</style>
</head>
<body>
<div class="container">
<h1>Longeva Care Page Change Detector</h1>
<div id="statusContainer" class="status
<?php
if (stripos($changeStatus, 'error') !== false) {
echo 'error';
} elseif ($changesDetected) {
echo 'changes-detected';
} else {
echo 'no-changes';
}
?>">
<?php echo htmlspecialchars($changeStatus); ?>
</div>
<div class="last-check">
Last checked: <?php echo htmlspecialchars($lastCheckTime); ?>
</div>
<?php if (!empty($hashInfo)): ?>
<div class="hash-info visible" id="hashInfoContainer">
<h2>Hash Information:</h2>
<div><?php echo $hashInfo; ?></div>
</div>
<?php endif; ?>
<button class="btn-refresh" onclick="location.reload();">Check Now</button>
</div>
<?php if ($playAlarm): ?>
<audio id="alarmAudio" loop>
<source src="alarm_1.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<script>
document.addEventListener('DOMContentLoaded', function() {
var audio = document.getElementById('alarmAudio');
audio.play().catch(function(error) {
console.error("Audio playback failed:", error);
});
// Stop the alarm after 5 minutes (300,000 milliseconds)
setTimeout(function() {
audio.pause();
audio.currentTime = 0;
}, 300000);
});
</script>
<?php endif; ?>
<!-- Optional: Show audio controls for debugging (can be removed in production) -->
<!--
<audio id="alarmAudioDebug" controls>
<source src="alarm_1.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
-->
</body>
</html>
Explanation of the Code
-
Server-Side (PHP):
- Error Reporting: Enabled for debugging purposes. Ensure to disable or adjust error reporting in a production environment.
- Logging: All activities and errors are logged to
change_detector.log with timestamps.
- Change Detection:
- Fetches the content of the specified URL using cURL.
- Generates an MD5 hash of the fetched content.
- Compares it with the previously stored hash (
previous_hash.txt).
- If a change is detected (i.e., the hash differs), it updates
previous_hash.txt and sets flags to indicate a change has been detected.
- Auto-Refresh: The HTML meta tag
<meta http-equiv="refresh" content="10"> ensures the page reloads every 10 seconds to perform the check automatically.
- Alarm Trigger: If a change is detected, the
$playAlarm flag is set to true, which includes the audio element and JavaScript to play the alarm.
-
Client-Side (HTML/CSS/JavaScript):
- Design:
- Utilizes Google Fonts for a clean look.
- Responsive design ensures compatibility across devices.
- Status messages are color-coded for immediate visual feedback.
- Alarm Functionality:
- If a change is detected, the
audio element with the source alarm_1.mp3 is played in a loop.
- JavaScript ensures the alarm stops after 5 minutes (300,000 milliseconds) to prevent it from playing indefinitely.
- User Interaction:
- A "Check Now" button allows users to manually trigger a check without waiting for the next auto-refresh.
- Hash Information:
- If a change is detected, the old and new hash values are displayed for reference.
-
Security and Best Practices:
- Input Sanitization: Although minimal user input is involved,
htmlspecialchars is used to prevent XSS attacks.
- Timeouts: cURL is set with a timeout to prevent the script from hanging indefinitely if the target URL is unresponsive.
- Error Handling: Proper error messages are logged and displayed to the user if issues arise during the check.
Additional Recommendations
-
Permissions:
-
Audio File:
- Place the
alarm_1.mp3 file in the same directory as index.php or adjust the src attribute of the audio element to the correct path.
- Ensure the audio file is accessible and properly encoded.
-
Production Considerations:
-
Enhancements:
- Notifications: Integrate email or SMS notifications for critical alerts.
- AJAX Polling: For a more seamless user experience without full page reloads, implement AJAX polling to check for changes in the background.
- Multiple URLs: Extend the functionality to monitor multiple URLs simultaneously.
Final Notes
This script provides a robust solution for monitoring changes on a specific webpage with immediate auditory alerts. It's essential to test the script thoroughly in your environment to ensure all permissions and dependencies (like the audio file) are correctly set up. Customize the design and functionalities as needed to fit your specific requirements.