Menu
Is free
check in
the main  /  Advice / PHP as content to determine the type of file. File Expansion File PHP

PHP as content to determine the type of file. File Expansion File PHP

The last line is close. You can use: if (mime_content_type ($ _ files ["fupload"] ["TMP_NAME"]) \u003d\u003d "image / gif") (...

In the case when I now work, my $ _Files .. ["Type"] reports itself as "text / csv", while Mime_Content_Type () and FinFO () (offered by others) report "Text / Plain". According to @deceze, $ _files .. ["Type"] Useful only to know which type of client considers it to be a file.

A WARNING : The following answer does not actually check the type of file. He checks only the name. It not suitable For real security goals.

Edit: Do not use this method, Since it does not perform security check. I leave this answer here so that no one makes the same mistake as I try to do it.

I tried the following, and it worked for me:

$ allowed \u003d array ("gif", "png", "jpg", "pdf"); $ filename \u003d $ _files ["input_tag_name"] ["NAME"]; $ Ext \u003d Pathinfo ($ FileName, PathInfo_Extension); If (! In_array ($ Ext, $ Allowed)) (Echo "Error";)

In PHP 5.5, I use this feature to receive a file type and check if there is an image:

Function GetFileType (Return Image_Type_To_Mime_Type);) // Get File Type $ File_Type \u003d GetFileType ("Path / To / Images / Test.png"); Echo $ File_Type; // Prints Image / PNG // 1. ALL IMAGES HAVE MIME TYPE STARTING WITH "IMAGE" // 2. No other non-image Mime Types Contain String "Image" in it

Then you could do:

If (Strpos ($ filetype, "image")! \u003d\u003d FALSE) (// this is an image)

This is a simple scenario with one row, which I often use.

$ image \u003d "/var/www/core/temp/image.jpg"; $ isimage \u003d Explode ("/", mime_content_type ()) \u003d\u003d "image";

Basically, I use Mime_Content_Type () to get something like "image / jpg", and then hack it "/" and check for the first element of the array to see if it says "image".

I hope it works!

Of course, you can check if it is an image with EXIF, but the best wayI think it's to do with FINFO as follows:

$ allowed_types \u003d array ("Application / PDF", "image / jpeg", "image / png"); $ FileInfo \u003d FINFO_OPEN (FileInfo_mime_Type); $ detected_type \u003d finfo_file ($ FileInfo, $ _files ["Datei"] ["TMP_NAME"]); if (! in_array ($ detected_type, $ allowed_types)) (DIE ("Please Upload A PDF or An Image");) Finfo_Close ($ FileInfo);

In addition to @deceze you can also finfo () Check the MIME type of files without an image:

$ finfo \u003d new finfo (); $ FILEMIMETYPE \u003d $ Finfo-\u003e File ($ Path. $ FileName, FileInfo_mime_Type);

Function AssignFilePreViews () ($ ("Input"). Change (Function (). Change ("Data-Preview-Container"); if (PRVCNT) (IF (this.files && this. Files) (var Reader \u003d new FileReader (); Reader.Onload \u003d Function (E) (VAR IMG \u003d $ (" "); img.attr (" src ", e.target.result); img.error (FUNCTION () ($ (PRVCNT) .html (" ");)); $ (PRVCNT) .html (" ") ; img.appendto (PRVCNT);) Reader.ReadasDataURL (this.files);))));) $ (document) .Ready (Function () (AssignFilePreviews ();));

It also processes the case when a file is selected with an invalid type (for example, PDF)

8 replies 8.

Never use $ _Files .. ["Type"]. The information contained in it is not checked at all, it is a user value. Check the type yourself. EXIF_IMAGETYPE is usually good choice:

$ ALLODTYPES \u003d Array (ImageType_png, imagetype_jpeg, imagetype_gif); $ DetectedType \u003d exif_imagetype ($ _ files ["fupload"] ["TMP_NAME"]); $ error \u003d! IN_ARRAY ($ DetectedType, $ ALLODTYPES); $ size \u003d getimagesize ($ filename); If ($ size \u003d\u003d\u003d False) (Throw New Exception ("($ FileName): invalid image.");) if ($ size\u003e 2500 || $ size\u003e 2500) (Throw New Exception ("($ FileName) : Image Too Large. ");) If (! $ Img \u003d @imagecreatefromstring (File_Get_Contents ($ FileName)) (Throw New Exception (" ($ FileName): Invalid Image Content. ");)

Checking the GETIMAGESIZE () prevents some DOS attacks, because we do not need to try to execute the imagecreatefromstring () from each file provided by the user who is not a file or a file too large. Unfortunately, according to PHP documents, it cannot be relying to check the content type content.

imageCreateFromString () Finally, trying to open the file as an image - if it is successful - we have an image.

2017-07-12 09: 05: 07Z

This is a simple single-line script that I often use.

$ image \u003d "/var/www/core/temp/image.jpg"; $ isimage \u003d Explode ("/", mime_content_type ()) \u003d\u003d "image";

Usually I use Mime_Content_Type () to get something like "image / jpg", and then blast it with "/" and check the first element of the array to see if it is "image".

I hope it works!

2017-10-18 22: 53: 49z

In PHP 5.5, I use this feature to get a type of file and check if the image:

Function GetFileType (Return Image_Type_To_Mime_Type);) // Get File Type $ File_Type \u003d GetFileType ("Path / To / Images / Test.png"); Echo $ File_Type; // Prints Image / PNG // 1. ALL IMAGES HAVE MIME TYPE STARTING WITH "IMAGE" // 2. No other non-image Mime Types Contain String "Image" in it

Then you can do:

If (Strpos ($ filetype, "image")! \u003d\u003d FALSE) (// this is an image)

Full list of pantomime types: http: //www.sitepoint .com / Web Funds / MIME Type-Full-List /

2015-06-11 16: 47: 46Z

The latter line is close. You can use: if (mime_content_type ($ _ files ["fupload"] ["TMP_NAME"]) \u003d\u003d "image / gif") (... p\u003e

In the case of which I now work, my $ _files .. ["Type"] reports itself as "text / csv", while Mime_Content_Type () and Finfo () (proposed by others) report "Text / Plain. ". As indicated @deceze, $ _files .. ["type"] is useful to know only about what type of client considers the file.

2018-08-09 19: 38: 14z

A WARNING: The following answer does not actually check the type of file. He only checks the name. It Not suitable For real security goals.

Edit: Do not use this methodSince it does not perform security check. I leave this answer here so that no one makes the same mistake as I try to do it.

I tried the following, and it worked for me.

The task of determining the expansion occurs in the development quite often - here and, and the analysis of the available files, and search for the file. In working with files on the server, there is also frequent solution Save the file is not with the source name, but the destination as the file name of the current value of the TimeStamp server. Solutions this task exists a lot for different programming languages. Although some decisions, first of all coming to mind, sometimes have to be refined due to the variety of file names that can only be. For a file named "MyFile.txt", you can safely offer to split the string into parts separated by the point and take the last one. But what to do with the files "my.file.txt" or if the extension is not specified "MyFile"?

In this article, consider such solutions.

For convenience, the file name will be set in a string variable:


$ filename \u003d "MyFile.txt";

// Other file name options
$ FileName \u003d. "File"; // not indicated expansion
$ filename \u003d "my.file.txt"; // Point in the file name
$ filename \u003d "dir / myfile.txt"; // File name indicating directory
?>

The simplest and most convenient, in my opinion, the solution to use the Pathinfo () function, which will return the associated array containing full name, expansion and directory of the file. After that, it remains to withdraw the necessary element of the array.



$ File_info \u003d Pathinfo ($ FileName);
return $ File_info ["Extension"];
}


?>

In order not to make your own function, you can simplify the code, specifying the value of Pathinfo_extension as the second parameter. In this case, the function will return not the entire array, but only the value of the expansion.


echo Pathinfo ($ FileName, Pathinfo_Extension);
?>

Both variants will correctly return the value of the extension "TXT", except for the case where the extension is not specified. Where there are no extensions, an empty string will be returned.

This solution is available for PHP, starting with version 4.0.3.


If, due to the PHP version or any other reason, this solution is not available, you can use traditional solution - breakdown of the file name of the file on the part between the points, believing that the last plot will be expansion.


function Get_File_Extension ($ FileName) (
return End (Explode (".", $ FileName));
}

echo Get_File_Extension ($ FileName);
?>

Here, the Explode () function breaks the string to an array of characters, separated by points, and the END () function returns the last element of the resulting array.

In this example, if the extension is not specified, i.e. There are no points in the file name, the source file name will be returned. In case the extension is there, it will be obtained correctly.

22

Please note that you may not need to use file extensions to determine the type of file. For example, to download the executable file with the extension. PNG. The type can also be easily forged by a malicious client for transmission as an image. Relying on this information, this is a risk for security..

For the file size, you already use $ _Files ["ImageFile"] ["Size"]; This is normal, I think, but you will know this only when the file has been loaded. However, no real way Check it before downloading, I'm afraid ...

You can find the JS code for the first advance extension check before the file is loaded, but you still have to check the server side, since everything that is being done on the client side is in essence unsafe.

Not sure that you can do the same on the size of the file, although ...

Some browsers can support a hidden field called max_file_size (see File Upload documentation); But not sure that it is really supported (never seen before, in fact, so, probably not :-()

As a remark, you probably want to configure upload_max_filesize, so that allows you to upload at least big as you want (by default it is usually installed in 2 MB, so it must be in order)

2

PHP is the scenario language on the server side, and if the images are on the client side, you cannot check their size before downloading via PHP .

2

You need two things:

your extension checking register-dependent:

If ($ STRTOLOWER ($ EXT \u003d\u003d "JPG")) (// do your stuff)

Check if the file actually contains the image. The easiest way to do is FileInfo:

$ FINFO \u003d FINFO_OPEN (FileInfo_mime_Type); Echo Finfo_File ($ Finfo, $ FileName); $ finfo_close ($ finfo);

An alternative method of checking is whether the file is actually loaded in the image library as GD. If your file can be successfully downloaded, this is an image.

Keep in mind that jpeg Images may have either .jpg, or extension.jpeg.

3

That's what I'm doing:

If ($ _ files ["UserPicture"] ["error"] \u003d\u003d 0) (// File Was uploaded OK, So it "s ok to proceed with the filetype check. $ Uploaded_type \u003d exif_imagetype ($ _ files [" UserPicture "] ["TMP_NAME"]); // What We Have Now IS A Number Representing Our File Type. Switch ($ uploaded_type) (Case "1": $ uploaded_type \u003d "gif"; break; Case "2": $ uploaded_type \u003d " JPG "; Break; Case" 3 ": $ uploaded_type \u003d" png "; break;))

Edit: It has the advantage of the work "in any browser", because it does not depend on the file name, or something user comes, except for "errors" the values \u200b\u200bof the array files that tell us that there was not really a mistake.

What is a MIME file type? How to define MIME file type pHP? How to install FileInfo module and configure a local server, assembling Denver.

MIME - standard describing the transmission different types data in e-mail, as well as a specification for encoding information and format messages in such a way that they can be sent over the Internet.

Pass Matchast

As such, the definition of MIME-type of a file is based on its extension (file). As you understand, this is a fairly conditional definition of MIME-type. For example, the image.jpg file (even if it is something else), on the JPG extension, MIME type will be defined: image / jpeg. Of course, you can analyze the content of the file and based on it to determine the correct MIME type, but this solution is not included in my note.

The main thing is that now you need to understand is the need for server magic.mime. The file where MIME types are described. As such, it is part of PHP. It happens that in the Apache Server folders you can find this file. In general, who is looking for, he will find. In theory, find out where Magic.mime can be considered the value of the option mime_magic.magicfile. From php.ini. For example:

However, this option will not return anything, however, try.

It should be noted, in order to determine the MIME file type, the FileInfo module has in PHP. In other words, you can always navigate, do you have the opportunity to find out or not, by the presence of this module. For example:

So if the module is, that is, the chance that it will work everything. In extreme cases, you can specify the path to your Magic.mime file.

Practice

Most. simple way The definitions of the MIME type file to the PHP tools is to use the MIME_CONTENT_TYPE () PHP function from the FileInfo module. For example:

As a result, we must get a string: image / jpeg.. Of course, if the image.jpg file exists, the FileInfo module is connected and Magic.mime available.

Note that the value of the MIME_CONTENT_TYPE () function must be a full path and file name, for which I used the Dirname design (__ File__). "image.jpg". It should also be remembered that this feature is considered obsolete (eng. deprecated) And in the future will be excluded from PHP. An alternative can serve as a solution written using PHP functions from the same FileInfo module:

Here, the FINFO_OPEN () function creates a FileInfo resource ($ FINFO). Taking into account the FileInfo_mime_Type constant available in Php version Not lower than 5.3.0, we will be able to get a MIME type of file (s).

I think it is already clear that the php-function finfo_file () using FileInfo resource ($ FINFO) returns us for information for specified File ($ FileName). In our case, this is a MIME type: image / jpeg.

Well, if all the above did not bring the result, you can write your own parser. There are also many options here. One of these is the parser of the Magic.mime file. No matter where he is, the main thing that he was.

I think to paint that yes, as it does not make sense - and so everything is more than clear. I just want to draw your attention to the path specified by me to the MIME.Types file. As you probably guessed, we are talking about local server. More precisely, about the assembly Denver. And here, we smoothly go to the installation of the module and configuring the server.

Installation and Setup

Let us remind you again: we are talking about a local server, the assembly of Denver. As you understand, we will need to refer to the php.ini file. It is in my folder: C: \\ WebServer \\ usr \\ Local \\ php5 \\. In it, we need to connect two extensions: php_fileinfo.dll and php_mime_magic.dll. For example, so:

Extension \u003d php_fileinfo.dll extension \u003d php_mime_magic.dll

I draw attention to the fact that the expansion data must exist. I have them in the folder: C: \\ WebServer \\ usr \\ Local \\ PHP5 \\ EXT \\.

Mime_magic.debug \u003d on mime_magic.magicfile \u003d "C: \\ WebServer \\ usr \\ Local \\ Apache \\ Conf \\ Magic.mime"

Note that for the mime_magic.magicfile option you need to register the full way and name. migic.mime.. That's actually all.