Jordan Dyckes Jordan Dyckes - 4 months ago 7
PHP Question

Why doesn't my simple filename extension check work?

// What's my mime?
$_mime = 'text/plain';
if ($_file[strlen($_file)-1] == 'j') { $_mime = 'text/javascript'; }
else { $_mime = 'text/css'; }

I really don't understand why the above does not work, my server will response with two input types either .min.js or .min.css

It should take the last character, step back one, which should either be j or s.

The response is always text/css regardless. Of course strict mime restriction then breaks my entire website, urgently need solution.


You're off by one, a common error.

Let's say your filename is script.js.

The length is 9, but since the count in an array starts from 0, the j is the 7th letter, and the s the 8th.

^       ^
0       8

So just do if ($_file[strlen($_file)-2] == 'j')

$file = 'script.js';

console.log('File name length:', $file.length);
console.log('First letter:', $file[0]);
console.log('Last letter:', $file[$file.length - 1]);
console.log('The letter you want:', $file[$file.length - 2]);

Also, I'm assuming $_file is a string with the name of your file.

Anyway, I hope you're aware you aren't doing a mime-type check, but just checking the file extension - this doesn't provide any security to you, and you cannot be sure about the mime-type of the file. You need to trust the source of the file. So do not use this way to determine the mime-type if the file is uploaded to your server by a third party.