i need your suggestions for checking image file. If a user will upload any file with changed extension type like (jpg,jpeg,bmp,png) how do we figure out that in PHP? I don't want to check only file type extentions but i want to know that the uploaded file is not a malicious file by changing it's extention type. Like: we have hack.php file and we change it with hack.jpg file so how to we identify that this is not a valid file.
Asked
Active
Viewed 715 times
-1
-
Why should that be of interest? If a user uploads something, then that is his own problem. Typically you only want to re-deliver that if it is requested. If someone uploaded a text file renamed somehow, then fine, he get's back a text file. – arkascha Nov 21 '18 at 08:11
-
Have you done anything on your own yet? You are expected to try to write the code yourself. Please read [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – brombeer Nov 21 '18 at 08:21
-
@arkascha that could open your application to security issues. – Federico klez Culloca Nov 21 '18 at 08:26
-
2@FedericoklezCulloca Can you explain how that is possible? – patrick Nov 21 '18 at 08:50
-
@FedericoklezCulloca Only if you actually use such uploaded data and integrate it into your application logic. Which of course no one does _specifically because_ you cannot in any way trust data uploaded from the client side. Yes, you can deliver a file that contains something else than what it appears to hold at first. So what? That is not a "security issue". – arkascha Nov 21 '18 at 08:58
-
@arkascha I was thinking of [this](https://www.trustwave.com/Resources/SpiderLabs-Blog/Hiding-Webshell-Backdoor-Code-in-Image-Files/) which is orthogonal to the issue at hand, but still – Federico klez Culloca Nov 21 '18 at 09:00
-
2@FedericoklezCulloca That requires [server code that executes user provided data](https://blog.sucuri.net/2013/07/malware-hidden-inside-jpg-exif-headers.html). A bad idea in the first place. – patrick Nov 21 '18 at 09:33
1 Answers
1
I will use mime_content_type if exists. Else execute linux command of file -i -b
on the file to get the answer.
Consider function as following:
function getFileType($file_name) {
if(! function_exists('mime_content_type')) {
$isUnix = strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN' && DIRECTORY_SEPARATOR === '/';
// check whether operating system is that of a UNIX type.
if ($isUnix) {
$type = null;
exec('file -i -b ' . realpath($file_name), $type);
$parts = @ explode(";", $type[0]); // can be of format text/plain; charset=us-ascii
return trim($parts[0]);
}
// the file program/command does not exist on Windows.
else {
return null;
}
} else {
return mime_content_type($file_name);
}
}
You can also use finfo-file is you prefer.

dWinder
- 11,597
- 3
- 24
- 39
-
Or you can spare yourself the shellout and use [`finfo_file`](http://php.net/manual/en/function.finfo-file.php) – Federico klez Culloca Nov 21 '18 at 08:25