Home > Software design >  How to check if a file is an archive before uploading it to a server?
How to check if a file is an archive before uploading it to a server?

Time:01-07

I need to check if a file that's about to be uploaded via input field is really an archive. For images I can just do $my_image['type'] to get the type, but if I do the same for a .rar file the returned type is 'application/octet-stream'. I've tried to open the file to check if it's an archive, only to find out later that apparently that can't be done to a file before it's uploaded.

Where do I go from here?

CodePudding user response:

Try to use pathinfo() function to get the file extension then check if it is an extension that corresponds to an archive file format that you want to support

$fileInfo = pathinfo($_FILES["my_file"]["name"]);
$fileExt  = $fileInfo["extension"];

if($fileExt == "zip" || $fileExt == "rar" || $fileExt == "tar" || $fileExt == "gz")
    // your file is an archive
else
    // your file is not an archive

You can also try another solution by using mime_content_type to get the MIME type of your uploaded file and check if it corresponds to an archive file format

  •  Tags:  
  • php
  • Related