How can i check if a file is archived (zip or rar) without knowing the extension. I need to find it using php.
I cannot use Fileinfo because its not installed and installation of any other packages on the server its out of the question.
UPDATE:
Zip module its not installed and i cannot install extra packages. I don't want to use mime_content_type because its deprecated
Thank you
Thanks to flu for the helpful link to the zip file specification.
To test whether a file is a zip archive, you can attempt to open it as a zip using
open_zip
function. For rar, you need to have PECL rar (preferably version at least 2.0.0) installed - see http://php.net/manual/en/book.rar.php for more details. The code could look like this:You may need to do a bit extra work if the archives are password-protected. Read the corresponding php manual pages for more details.
Read first 10 bytes of the file. If they are (80, 75, 3, 4, 20, 0, 0, 0, 8, 0) it is a ZIP file. RAR files have the following 7 first bytes: (82, 97, 114, 33, 26, 7, 0) If you open a ZIP file in a text editor (for instance, Notepad++) you will see: PK[ETX][EOT][DC4][NUL][NUL][NUL][BS][NUL]....-> the Ascii codes for the characters are listed above. For the RAR files the picture is: Rar![SUB][BEL][NUL].... So, just read the 10 first bytes of a file and you can tell if it is ZIP or RAR archive. Cheers
The fileinfo functions should help you with this, by checking the file's mime type:
Output from
od -c
:You could use something like this:
And my output:
You could output the info from unix file command and parse it(assuming you can execute system commands, which is bad practice).
This is example of centos "file filename" output.
also like other people suggested, you could read few bytes and check if they match signature.
for rar
for zip