Reputation: 6207
lets consider this code:
if (md5_file(__FILE__) != 'MD5 CODE')
{
echo 'fail!';
}
of corse it will always fail whatever to write to he if conditional. Or is there a solution?
Upvotes: 1
Views: 825
Reputation: 21
There are ways to 'self-validate' with a hash function. One of the tricks would be to store the expected md5 hash in the first line of the php script, and then validate the file after that line.
<?php
$md5Expected="md5string"; $sizeExpected=<bytes>;
<Code to validate. Includes last line.>
?>
The function to check this might look a bit like:
function validateMeContents( $md5Expected, $sizeExpected ) {
$checkFilename = basename( $_SERVER['PHP_SELF'] );
// the first 2 lines are not checked
$fileContents = array_splice( file( $checkFilename ), 2 );
$md5Contents = md5( implode( $fileContents ) );
$mySize = filesize( $checkFilename );
return( ( $md5Expected == $md5Contents ) and ( $sizeExpected == $mySize ) );
}
Note that you probably want to check the size of the file, which would take into account the first 2 lines of code.
Valid points have been raised that the validation is probably best done by an external 3rd party, such as the OS. Look into md5sum -c
or sha1sum -c
.
Also, you probably have bigger issues if you are worried about files on the server getting modified in an uncontrolled manner. If this is because there is a freedom to modify the files on the server, that policy may want to be re-evaluated.
Upvotes: 2
Reputation: 3160
You will never be able to execute that code correctly, because whenever you update the MD5_CODE
, the hash of the file will change.
The only way you can check a file is from another file, but not from itself. Unless you put the hash in an external file:
$hash = file_get_contents('myhash.txt');
if (md5_file(__FILE__) != $hash) {
print "WARNING: Code modified!";
}
Upvotes: 3