1

What is the most elegant and efficient way of comparing a string against text file in PHP.

The flow:

I have a file on server var\user\rinchik\file\fileName\version0.txt.

user comes on the web-site, does his thing and gets $string with N characters length.

I need to check is this string is identical to the contents of var\user\rinchik\file\fileName\version0.txt. If it is then do nothing. If its not then save this string here: var\user\rinchik\file\fileName\version1.txt.

Should i just read the file version0.txt into another string then hash both of them and compare hashes?

Or there is some hidden magic method like: save new string as version1.txt and the run something like file_compare('version0.txt', 'version1.txt'); and it will do the trick?

4

3 回答 3

3

您应该将文件读version0.txt入字符串 $string1 并检查是否$string == $string1(我认为没有必要散列$stringand $string1)。

PHP 中没有内置函数可以比较两个文件的内容。

另一种方式,您可以使用 shell 命令diff。比如exec('diff version0.txt version1.txt', $res, $rev)和检查返回值if ($rev == 0) {...}

于 2013-03-08T19:25:09.970 回答
1

由于您知道字符串的长度,因此您可以先检查strlen($string) == filesize($filename). 如果它们不同,您甚至不需要检查内容。

如果它们相同,那么您可以像 Marc 的回答那样使用/对$string == file_get_contents($filename)它们进行哈希处理,以验证内容是否相同。md5md5_file

当然,如果生成字符串的方法意味着文件总是相同的长度(例如散列函数的结果),那么检查文件大小是没有意义的。

于 2013-03-08T19:25:15.703 回答
0

快速而肮脏的方法,无需先将字符串写入文件:

if (md5($string) == md5_file('/path/to/your/file')) {
  ... file matches string ..
} else {
  ... not a match, create version1.txt
}
于 2013-03-08T19:22:42.160 回答