Link to home
Create AccountLog in
Avatar of sasnaktiv
sasnaktivFlag for United States of America

asked on

How can I prevent the uploading of a file using file extensions?

Hi Guys,
This question should be an easy one to answer for any Expert at EE.
How can I block all & any file (with the following extensions: .html ; .php; .exe;) from uploading to our server?


Currently I'm using the following line of code successfully, but it doesn't go far enough — it's limited to exact filenames.

This is my code:

[code]
if($File=="index.html" || $File=="index.php" || $File=="default.html" || $File=="default.php")
{ echo "Sorry! You can't upload that kind of file";}
[/code]
Thanks for the help.

ASKER CERTIFIED SOLUTION
Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of sasnaktiv

ASKER

That's interesting David,
I'll give both approaches a shot tomorrow and let you know how it works out.
At first glance it looks quite logical.
Thanks
Sas
Maybe put the files you will accept (or will not accept) in an array and check if the item is in that array?

https://www.php.net/manual/en/function.in-array.php

$not_allowed= array("html ", "php", "exe");
if (in_array($file, $not_allowed )) {
    echo "Sorry! You can't upload that kind of file";
}

Open in new window


To David & Scott,
Thanks for the help guys.

To David:
I'm having trouble getting the FilePath for your very first line of code.
$pathparts = pathinfo('/www/htdocs/inc/index.php');

Open in new window

I tried using $FilePATH = $_SERVER['PATH_INFO']; to get the path, but it comes back empty.
So I made one minor change to that line of code.
$pathparts = pathinfo('$File');

Open in new window

Presto! It worked!


To Scott:
Your code looks extremely simple and makes a lot of sense—perfect sense. I like it. But it fails!
Simply saying it fails does not help me :)  You have try and see what the issue is and adjust.

Try this

$file = "somefile.php"; //FILE WE AR CHECKING
$file_type = substr($file,-3);  //GET THE FILE TYPE BY THE LAST THREE CHARACTERS

$not_allowed= array("html ", "php", "exe");  // NOT ALLOWED LIST

if (in_array($file_type, $not_allowed )) { // CHECK IF FILE IS IN THE NOT ALLOWED LIST
    echo "Sorry! You can't upload that kind of file";
} else {

    echo "This is a good file";
}

Open in new window


https://www.php.net/manual/en/function.substr.php
https://www.php.net/manual/en/function.in-array.php
Okay Guys. Both solutions function brilliantly.
Is there any reason why one version should be better than the other?
Sas
What works is what counts. We could probably come up with 10 more options.

If you were to create a database of file types, then instead of

$not_allowed= array("html ", "php", "exe");  // NOT ALLOWED LIST

you would replace that with the array generated by the query