Determine the type of file uploaded in PHP


I am working with the upload and reading of a spreadsheet file and I want to check that its type is correct, according to the php documentation the key type of the global variable $_FILES


The MIME type of the file, if the browser provided this   information. An example would be "image / gif". This MIME type, without   However, it is not checked on the PHP side and therefore does not   Guarantees its value.

Which means that the browser does not assure us the correct mime and it is not good to trust it. The question is how to get the right type of mime type because I have seen several functions of the php to do it as mime_content_type and it happens that these functions receive the actual file path (which I do not have, because I only read the file but not I upload it to the server), I just have the file path temp that returns $_fILES . Does anyone know how to achieve this? I remain in any doubt.

asked by jjoselon 16.10.2018 в 17:50

2 answers


greetings I leave you a simple but useful code to validate the extensions you want:

$formatos_permitidos =  array('doc','docx' ,'xls');
$archivo = $_FILES['doc_file']['name'];
$extension = pathinfo($archivo, PATHINFO_EXTENSION);
if(!in_array($extension, $formatos_permitidos) ) {
    echo 'Error formato no permitido !!';

PATHINFO .- Returns information about a file (DOCUMENT / ARCHIVE, ETC ...) this pathinfo has as parameter:



We use the extension to get the extension of our document. and by this we validate in an if ..

Official Documentation ... more info

I hope it serves you and I can guide you .. !!

answered by 16.10.2018 / 18:17

Well what I do in your case would be to get the name of the file I'm uploading with:


This would show us something like:

      [0] => archivo1.jpg
      [1] => archivo2.xls

Then I do a explode () of the name to get the extension of the file like this:

$archivo = $_FILES["fichero_usuario"]["name"][0]; //archivo1.jpg
$arrayString = explode(".", $archivo); //array(archivo1, jpg)
$extension = end($arrayString); //jpg

As you'll see I do a explode with the (.) character, which usually follows the extension of the file, that would generate a array strong> which I store in $ arrayString and then apply a end () to get the last element of the array that will contain the extension. Why a end () ? because maybe the name of the file has points then we make sure to get the extension with the end () . Then with that you do a validation as you want or very mundane as:

if($extension != "xls"){
  echo "No es valido";
  echo "Valido";

I hope it serves you.

answered by 16.10.2018 в 18:15