In website development and maintenance, the integrity of static resources (such as CSS, JavaScript files, images, etc.) is crucial to ensuring the security of the site and a smooth user experience. However, static resources may sometimes be tampered with, leading to the loading of erroneous content or even security risks. This article will explain how to use PHP's built-in md5_file() function to quickly monitor and detect whether static resources on a website have been altered.
md5_file() is a PHP function used to compute the MD5 hash value of a file. It accepts a file path as a parameter and returns a 32-character hexadecimal string representing the content of the file. By comparing the MD5 value of the file, you can quickly determine if the content has changed.
Regularly scan static resources for tampering after the website goes live.
Compare version files to confirm the integrity of deployment files.
Monitor the security of third-party library files.
First, calculate and save an initial MD5 value for the static resource files.
Periodically traverse these files and recalculate their MD5 values.
Compare the newly calculated MD5 values with the previously saved ones.
If the MD5 values do not match, it indicates that the file has been modified or tampered with.
The following example demonstrates how to use PHP's md5_file() function to monitor whether static resources in a specified directory have been tampered with.
<?php
// Monitoring directory
$directory = __DIR__ . '/static';
<p>// File to save MD5 values (stored in JSON format)<br>
$md5RecordFile = <strong>DIR</strong> . '/md5_records.json';</p>
<p>// Read historical MD5 records<br>
$oldMd5Records = file_exists($md5RecordFile) ? json_decode(file_get_contents($md5RecordFile), true) : [];</p>
<p>// Get all static files in the directory<br>
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));<br>
$changedFiles = [];<br>
$newMd5Records = [];</p>
<p>foreach ($files as $file) {<br>
if ($file->isFile()) {<br>
$filePath = $file->getPathname();<br>
// Calculate the current MD5 value of the file<br>
$md5 = md5_file($filePath);</p>
$relativePath = str_replace($directory . DIRECTORY_SEPARATOR, '', $filePath);
$newMd5Records[$relativePath] = $md5;
// Compare old MD5 with new MD5
if (!isset($oldMd5Records[$relativePath]) || $oldMd5Records[$relativePath] !== $md5) {
$changedFiles[] = $relativePath;
}
}
}
// Output detection results
if (count($changedFiles) > 0) {
echo "The following files have been modified or added:\n";
foreach ($changedFiles as $changedFile) {
echo "- " . $changedFile . "\n";
}
} else {
echo "No files have been modified.\n";
}
// Save the latest MD5 records
file_put_contents($md5RecordFile, json_encode($newMd5Records, JSON_PRETTY_PRINT));
?>
The static directory is where the static resources are stored; you can adjust the path according to your actual project.
The MD5 record file md5_records.json is used to store the MD5 value of each file for easy comparison later.
This script will output the list of files that have been modified or added.
You can set this script to run as a scheduled task (e.g., cron on Linux) for automated monitoring.
Automatic Alerts
When a file modification is detected, administrators can be notified via email or SMS to promptly address potential risks.
Whitelist Management
For files that change frequently but do not affect security, establish a whitelist to avoid false positives.
Stronger Encryption Hash Algorithms
For higher security, consider using hash_file('sha256', $filePath) instead of md5_file().
Combine with Version Control Systems
Use tools like Git to manage static resources, combined with md5_file() for double assurance of file security.
Using PHP's md5_file() function to monitor and detect tampering of static resources on a website is a simple and efficient method. It helps developers quickly identify the risk of file tampering, ensuring the integrity and security of the website's content. By combining automated scripts and alert mechanisms, the efficiency of website security maintenance can be significantly improved.