To synchronize the timer across the admin and member panels in PHP and JavaScript, you can follow these steps:
**1. Server-side PHP Script (timer.php):**
```php
<?php
session_start();
// Function to get the current timer value
function getTimerValue() {
if (isset($_SESSION['timer'])) {
return $_SESSION['timer'];
} else {
// Default timer value (in seconds)
return 120; // 2 minutes
}
}
// Function to update the timer value
function updateTimerValue($newValue) {
$_SESSION['timer'] = $newValue;
}
// Check if the request is to get or update the timer value
if (isset($_GET['action'])) {
// Get the current timer value
if ($_GET['action'] === 'get') {
echo getTimerValue();
}
// Update the timer value
if ($_GET['action'] === 'update') {
if (isset($_GET['new_value'])) {
$newValue = intval($_GET['new_value']);
updateTimerValue($newValue);
echo "Timer updated successfully!";
} else {
echo "Error: New timer value not provided.";
}
}
}
?>
```
**2. Client-side JavaScript for Admin and Member Panels:**
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timer Sync</title>
</head>
<body>
<h1>Timer</h1>
<div id="timer"></div>
<script>
// Function to fetch the current timer value from the server
function getTimerFromServer() {
fetch('timer.php?action=get')
.then(response => response.text())
.then(timerValue => {
document.getElementById('timer').innerText = timerValue;
});
}
// Function to update the timer value on the server
function updateTimerOnServer(newValue) {
fetch(`timer.php?action=update&new_value=${newValue}`)
.then(response => response.text())
.then(message => {
console.log(message);
});
}
// Function to start the timer
function startTimer(duration) {
let timer = duration;
setInterval(function () {
if (timer > 0) {
timer--;
document.getElementById('timer').innerText = timer;
} else {
// Timer has expired, update the timer value on the server
updateTimerOnServer(timer);
}
}, 1000);
}
// Fetch the initial timer value and start the timer
getTimerFromServer();
startTimer(parseInt(document.getElementById('timer').innerText));
</script>
</body>
</html>
```
**Usage:**
- Embed the above HTML code in both the admin and member panels.
- The PHP script (`timer.php`) manages the timer value on the server-side and updates it as needed.
- The JavaScript code fetches the current timer value from the server and updates it in real-time. It also updates the server with the new timer value when the timer expires.
Ensure that you include appropriate error handling and security measures in your actual implementation. Additionally, you can customize the timer duration and update interval according to your requirements.