Automate Your PHP Server Security: Real-Time File Monitoring with Email Alerts and JSON Integration
Introduction
Is your PHP-based server as secure as it could be? Monitoring changes to critical files is essential to protect your applications and data from unauthorized modifications. This article introduces a powerful PHP script, directory_monitor.php, which automatically scans directories for recent file modifications, sends email alerts, and outputs data in JSON format—ideal for integration with external monitoring apps or services.
We’ll cover installation, configuration, and setup so you can enhance your server security with minimal effort.
TL;DR: This script helps you monitor files on your PHP-based server for unauthorized changes, provides JSON responses for easy integration, and sends real-time email notifications.
Installation
To get started, make sure you have PHP 7.4 or higher and follow these steps:
1. Install PHPMailer
To simplify the code, we use the PHPMailer
library for sending email notifications. You can install PHPMailer
via Composer:
composer require phpmailer/phpmailer
After installation, ensure that PHPMailer
is accessible in the specified path. For this script, we’re using:
require '../vendor/autoload.php';
Adjust the path to autoload.php
as needed based on your project structure.
2. Set Up Directory Paths and Permissions
- Ensure PHP has read permissions for directories you’re monitoring and write permissions for the
lastmodified.json
file, which stores the most recent file modification states. - SMTP Access: Make sure you have valid SMTP credentials to send email notifications.
3. Update to the Latest PHP Version (Recommended)
For optimal performance, security, and compatibility, it’s recommended to update your server to the latest stable version of PHP. As of November 2023, the latest stable version is PHP 8.3.
Updating to the latest PHP version not only ensures better speed and resource handling but also provides enhanced security features to safeguard your applications. You can download the latest version from the official PHP website:
Make sure to test your application in a staging environment after updating, as some code or extensions may require adjustments to be compatible with the latest PHP features.
Requirements
- PHP 7.4 or Higher: Essential for compatibility with
PHPMailer
. - PHPMailer: Installed via Composer, as outlined in the installation section.
- File System Permissions: Ensure that PHP has necessary permissions for target directories and files.
- Email Server Access: SMTP server credentials are required to enable email notifications.
Limitations
- Scalability: This script is best for small to medium-sized directories. Large directories with many nested files may lead to performance issues.
- Limited Real-Time Capabilities: This script is not a real-time monitoring tool but can be executed at regular intervals through a cron job.
- Email Notifications: Multiple modifications in a short period will trigger multiple emails. To avoid excessive notifications, consider running the script less frequently or adjusting it to batch notifications.
- No Built-in Logging: There is no built-in logging for errors or issues, such as failed emails. Adding logging functions would improve reliability.
- Excludes Certain Changes: This script detects modification times but does not check file content if modification time is unchanged.
Script Overview
Key Features
- Directory Scanning: Recursively scans specified directories for modified files.
- Customizable Time Period: Monitors changes within a set period (e.g., 24 hours).
- Ignored Paths: Exclude specific files and directories from monitoring.
- Email Notifications: Sends email notifications when changes are detected.
- JSON Output: Outputs results in JSON format, ready for integration with external monitoring apps.
Note: The following script includes placeholders for sensitive information. Replace these placeholders with your actual values before deployment.
PHP Script: Real-Time Directory Monitoring and Notifications
Here’s the full PHP script, saved as directory_monitor.php
. Follow the instructions to configure it for your environment.
<?php
require '../vendor/autoload.php'; // Ensure PHPMailer is included
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
// Directory to search
$directory = '/path/to/your/directory';
$lastSavedFile = 'lastmodified.json'; // File to compare with
// Paths to ignore
$ignorePath = [
'/path/to/your/directory/lastmodified.json',
'/path/to/your/directory/config-file.php',
'/path/to/your/directory/log-file.log'
];
// Time period for modification (1 day in seconds)
$timePeriod = 86400; // 24 hours
// Set timezone (example: Pacific Time)
date_default_timezone_set('America/Los_Angeles');
// Function to search for files modified within the last day
function findRecentlyModifiedFiles($dir, $timePeriod, $ignorePath) {
$modifiedFiles = [];
$files = scandir($dir);
foreach ($files as $file) {
if ($file == '.' || $file == '..') continue;
$filePath = $dir . '/' . $file;
if (in_array($filePath, $ignorePath)) continue;
if (is_dir($filePath)) {
$modifiedFiles = array_merge($modifiedFiles, findRecentlyModifiedFiles($filePath, $timePeriod, $ignorePath));
} else {
if (time() - filemtime($filePath) < $timePeriod) {
$modifiedFiles[] = [
'path' => $filePath,
'time' => filemtime($filePath)
];
}
}
}
return $modifiedFiles;
}
// Get recently modified files
$recentFiles = findRecentlyModifiedFiles($directory, $timePeriod, $ignorePath);
// Sort files by modification time, latest first
usort($recentFiles, function($a, $b) {
return $b['time'] - $a['time'];
});
// Keep only the latest 10 modified files
$latestFiles = array_slice($recentFiles, 0, 10);
// Load last saved files if available
$lastSaved = [];
if (file_exists($lastSavedFile)) {
$lastSavedContent = file_get_contents($lastSavedFile);
$lastSaved = json_decode($lastSavedContent, true);
}
$response = [];
if (empty($lastSaved) || $latestFiles !== $lastSaved) {
$changedFiles = array_filter($latestFiles, function($file) use ($lastSaved) {
foreach ($lastSaved as $lastFile) {
if ($file['path'] === $lastFile['path'] && $file['time'] === $lastFile['time']) return false;
}
return true;
});
if (!empty($changedFiles)) {
file_put_contents($lastSavedFile, json_encode($latestFiles));
$response['changed_files'] = $changedFiles;
sendEmailNotification($changedFiles);
}
}
// Output JSON response for integration
header('Content-Type: application/json');
echo json_encode($response);
function sendEmailNotification($changedFiles) {
$mail = new PHPMailer(true);
try {
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your-email@example.com';
$mail->Password = 'your-password';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
$mail->Port = 465;
$mail->setFrom('your-email@example.com', 'File Change Notifier');
$mail->addAddress('recipient@example.com');
$mail->isHTML(true);
$mail->Subject = 'File Change Notification';
$checkTime = date('Y-m-d H:i:s');
$body = "<p>File change notification on: <strong>{$checkTime} PST</strong></p>";
$body .= "<p>The following files have changed or been added:</p><ul>";
foreach ($changedFiles as $file) {
$changeTime = date('Y-m-d H:i:s', $file['time']);
$body .= "<li><strong>File:</strong> {$file['path']} <br> <strong>Time of Change:</strong> {$changeTime} PST</li>";
}
$body .= "</ul>";
$mail->Body = $body;
$mail->send();
} catch (Exception $e) {
error_log('Mail could not be sent. Mailer Error: ' . $mail->ErrorInfo);
}
}
?>
Automating the Script with a Cron Job
To keep this monitoring script running on a regular basis, you can automate its execution using a cron job. This can be done either via the command line or through cPanel if it’s available to you.
Setting Up a Cron Job via cPanel
- Log in to cPanel and navigate to the Cron Jobs section under “Advanced.”
- In the Add New Cron Job area:
- Choose the frequency at which you’d like the script to run, such as every 30 minutes, hourly, or daily.
- In the Command field, enter:
/usr/local/bin/php /path/to/your/directory_monitor.php
Replace
/path/to/your/directory_monitor.php
with the actual path of the script on your server.
- Save the cron job, and it will execute on the set schedule.
Setting Up a Cron Job via Command Line
- Open the Crontab Editor:
crontab -e
- Add the Cron Job:
- Every 30 minutes:
*/30 * * * * /usr/bin/php /path/to/your/directory_monitor.php
- Every hour:
0 * * * * /usr/bin/php /path/to/your/directory_monitor.php
- Daily at midnight:
0 0 * * * /usr/bin/php /path/to/your/directory_monitor.php
- Every 30 minutes:
- Save and Exit: Save the changes to the crontab, and the cron job will begin running at the specified intervals.
Conclusion
By implementing this directory monitoring script, you’re taking proactive steps to safeguard your PHP-based server from unauthorized modifications and potential security risks. This script’s ability to send email alerts, provide JSON responses for easy integration, and work seamlessly with cron jobs makes it a powerful tool for real-time server monitoring.
Remember, keeping your PHP version updated—currently PHP 8.3 as of November 2023—not only enhances performance but also fortifies your server’s security posture. For more advanced tracking methods and other essential security practices, check out our complete guide on PHP server protection.
Take control of your server’s security with this automated monitoring solution, and rest assured knowing you have an extra layer of protection watching over your files!