Created
April 11, 2018 10:01
-
-
Save Werninator/3cbb006f682d4410e7a5a18a1e6db1a3 to your computer and use it in GitHub Desktop.
Compare two files in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Compare the contents of two files and return if they're the same | |
* | |
* modified version of: | |
* https://jonlabelle.com/snippets/view/php/quickly-check-if-two-files-are-identical | |
* | |
* @param string $fileOne path to file One | |
* @param string $fileTwo path to file two | |
* @return bool | |
*/ | |
function compareFiles($fileOne, $fileTwo) { | |
if (!file_exists($fileOne) | |
|| !file_exists($fileTwo) | |
|| filetype($fileOne) !== filetype($fileTwo) | |
|| filesize($fileOne) !== filesize($fileTwo) | |
|| !$fp1 = fopen($fileOne, 'rb')) | |
return false; | |
if (!$fp2 = fopen($fileTwo, 'rb')) { | |
fclose($fp1); | |
return false; | |
} | |
$same = true; | |
while (!feof($fp1) && !feof($fp2)) { | |
if (fread($fp1, 4096) !== fread($fp2, 4096)) { | |
$same = false; | |
break; | |
} | |
} | |
if (feof($fp1) !== feof($fp2)) | |
$same = false; | |
fclose($fp1); | |
fclose($fp2); | |
return $same; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment