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 には、2 つのファイルの内容を比較できる組み込み関数はありません。

別の方法として、シェル コマンドを使用できますdiffexec('diff version0.txt version1.txt', $res, $rev)戻り値などを確認しますif ($rev == 0) {...}

于 2013-03-08T19:25:09.970 に答える
1

文字列の長さはわかっているので、最初に確認できますstrlen($string) == filesize($filename)。内容が異なる場合は、内容を確認する必要さえありません。

それらが同じである場合は、マークの回答のように を実行するか、 /$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 に答える