Current Location: Home> Latest Articles> PHP Tutorial: How to Develop a Simple and Practical File Comparison Feature

PHP Tutorial: How to Develop a Simple and Practical File Comparison Feature

M66 2025-07-20

How to Develop a Simple File Comparison Feature with PHP

With the development of information technology, file processing has become increasingly important in daily work. We often need to compare two files to identify differences for further processing. Using PHP's built-in functions, it's easy to create a simple file comparison feature. This article explains the implementation process in detail and provides code examples.

Preparing the Files to Compare

First, determine the paths of the two files to compare. Here, we assume the file names are file1.txt and file2.txt, both located in the same directory.

Reading File Contents

You can use the file_get_contents() function to read the file contents into variables:

$file1 = file_get_contents('file1.txt');
$file2 = file_get_contents('file2.txt');

Comparing File Contents

To find differences between the two files, we compare their contents character by character using PHP string functions. The example code is as follows:

$diff = '';
$length = max(strlen($file1), strlen($file2));
for ($i = 0; $i < $length; $i++) {
    if (($file1[$i] ?? '') !== ($file2[$i] ?? '')) {
        $diff .= "{$file1[$i] ?? ' '} and {$file2[$i] ?? ' '} are different\n";
    }
}

In this code, we loop through each character of the two files and record any differences in the $diff variable. The null coalescing operator ?? is used to avoid errors if the files have different lengths.

Outputting the Comparison Result

Display the difference information on the page while preserving formatting for easy reading:

echo "<pre>{$diff}
";

Complete Example Code

$file1 = file_get_contents('file1.txt');
$file2 = file_get_contents('file2.txt');

$diff = '';
$length = max(strlen($file1), strlen($file2));
for ($i = 0; $i < $length; $i++) {
    if (($file1[$i] ?? '') !== ($file2[$i] ?? '')) {
        $diff .= "{$file1[$i] ?? ' '} and {$file2[$i] ?? ' '} are different\n";
    }
}

echo "<pre>{$diff}
";

Conclusion

The above method demonstrates how to implement a basic file content comparison feature using PHP. In real projects, more complex comparison logic and optimizations may be required, such as line-by-line comparison and highlighting differences. However, this example provides a useful reference for beginners and quick implementations of file difference detection.