I’m reviewing code that was written by another developer. The code tries to open a file, and sets $canOpen based on success/failure.
$fh = @fopen('files.php', 'a+');
if (!$fh){
fclose($fh);
$canOpen = false;
} else {
$canOpen = true;
}
What I find strange is that it also tries to close the file but only when the open fails if (!$fh). Does this make sense? Shouldn’t the close be in the else statement when the file was successfully opened?
No, it makes no sense.
If
!$fhis met as a condition, it means the$fhcontains booleanFALSE(or possibly, in the event of some weird internal PHP error,NULL). So what you are effectively doing is:…which is pointless and will result in an error.
And, if all you’re trying to do is populate the
$canOpenvariable and not do anything useful with the file handle, wouldn’t a combination ofis_file(),is_readable()andis_writable()suffice?