Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to recognize a filetype in php [closed]

Tags:

php

file-type

What's the best way to discover a file's filetype within php? I heard that the browser may be tricked, so what's a better way of doing this?

like image 437
LuRsT Avatar asked Jan 19 '09 14:01

LuRsT


People also ask

How would you determine if a given path is a file in PHP?

The is_dir() function in PHP used to check whether the specified file is a directory or not. The name of the file is sent as a parameter to the is_dir() function and it returns True if the file is a directory else it returns False.

Can PHP read from file?

PHP Read File - fread()The fread() function reads from an open file. The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.


2 Answers

You can use finfo_file

<?php
echo finfo_file(finfo_open(FILEINFO_MIME), "foo.png");
?>
like image 134
Carlo Avatar answered Sep 27 '22 19:09

Carlo


Look at "magic numbers." The first few bytes of files usually identify what type of file it is. For example, the firts few bytes of a GIF are either 47 49 46 38 37 61 or 47 49 46 38 39 61, ASCII for GIF89a or GIF87a. There are many other "magic numbers." See http://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files

EDIT: I believe this is more reliable than MIME functions on PHP.

like image 30
stalepretzel Avatar answered Sep 27 '22 19:09

stalepretzel