rinchik
rinchik

Reputation: 2670

PHP compare string against text file on the fly

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?

Upvotes: 1

Views: 2481

Answers (3)

Skydiver
Skydiver

Reputation: 413

You should read the file version0.txt into a string $string1 and check if $string == $string1 (I think it's not necessary to hash $string and $string1).

There is no build-in function in PHP which can compare the contents of two files.

Another way, you can use shell command diff. Such as exec('diff version0.txt version1.txt', $res, $rev) and check the return value if ($rev == 0) {...}.

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Since you know the length of the string, you can first check strlen($string) == filesize($filename). If they are different, you don't even need to check the contents.

If they are the same, then you can just do $string == file_get_contents($filename), or hash them with md5/md5_file as in Marc's answer, to verify the contents being identical.

Of course, if the method of generating the string means that the file will always be the same length (such as the result of a hash function) then there's no point in checking the file size.

Upvotes: 1

Marc B
Marc B

Reputation: 360732

Quick and dirty method, without having to write the string to a file first:

if (md5($string) == md5_file('/path/to/your/file')) {
  ... file matches string ..
} else {
  ... not a match, create version1.txt
}

Upvotes: 0

Related Questions