Reputation: 1122
I am writing a scanner that will look for possibly hacked/malware files. One requirement is to check if a zip (or any compressed) file is password-protected using some PHP function.
I don't want to add any extra software requirements, so should work on multiple servers, using PHP 5.3+ . (Yes I know that 5.3 is old, but the process may need to run on older PHP installations.) If this detection is available in newer PHP versions, then I could have code that would run only on newer PHP version.
I can use the file_get_contents()
function to read the file's contents into a string. How do I check that string for an indication that the zip file is password-protected? Note that I don't want to uncompress the file, just check it for password-protection.
Thanks.
Upvotes: 2
Views: 1968
Reputation: 1122
This code appears to work, but might be improved.
The process seems to involve two steps:
use zip_open to open the file, returning a resource. No resource, zip couldn't be opened, so it might be passworded
use zip_read to read the files inside the zip. If fails, then might be passworded
In either of those two cases, return true, indicating probable password on the zip file.
// try to open a zip file; if it fails, probably password-protected
function check_zip_password($zip_file = '') {
/*
open/read a zip file
return true if passworded
*/
if (!$zip_file) { // file not specified
return false;
}
$zip = zip_open($zip_file); // open the file
if (is_resource($zip)) { // file opened OK
$zipfile = zip_read($zip); // try read of zip file contents
if (!$zipfile) { // couldn't read inside, so passworded
return true;
}
else
{ // file opened and read, so not passworded
return false;
}
} else { // couldn't open the file, might be passworded
return true;
}
return false; // file exists, but not password protected
}
Note that the code only determines that the files inside the zip can't be accessed, so they are probably password-protected. The code doesn't try to do any processing of files inside the zip.
Upvotes: 3