$_files

They have: 53 posts

Joined: Oct 2005

Hi all!

I have a question: I am constructing a form where the user can upload a file.
I need however to verify that the file uploaded is a TEXT file.

Is $_FILE['userfile']['type'] what I need? I am asking this because no matter if I upload a .txt or a .gif file, PHP says they are both $_FILE['userfile']['type']='text' and so, they are both uploaded on the server, whereas there should be only .txt file uploaded and not the .gif file.

In general, how can I allow only text files to be uploaded?
(Of course, i can't rely much on the extension I believe)..

Thanx

Busy's picture

He has: 6,151 posts

Joined: May 2001

using $_FILES['userfile']['type'] is not a very good validation as it works off mime type and it can be forged and browsers do different things with them.
php.net reccomend the use of $_FILES['userfile']['error']
here is a script on the php.net site for allowing a txt file upload

They have: 53 posts

Joined: Oct 2005

Busy, thanx for your time,
but this code, if I got it correctly, checks fro file extensions.
My question is what can I do to prevent people from uploading .exe files for instance, changing the .exe to .txt.

I use :

if ($_FILES['userfile_PFAM']['type']='text/plain')
{then OK}

else
{wrong file type}

but it doesn't seem to work. PHP uploads both text files and .exe files.
Any thoughts?

Busy's picture

He has: 6,151 posts

Joined: May 2001

Do a check on extensions, something like, if it has .exe,.doc,.html,.php,.asp ... then fail
I know how to check for images, but not txt files, I guess by extension, by mime type and something

It's pretty scary allowing text files, I'd never do it for the security aspect of it, even images can be faked which is bad enough.

Biggest problem you have is people making a rouge script and renaming it .txt, if the file they made is a .php one for example it could run when you opened it.

Can you not do it where as the data is put into a form (textarea) and uploaded to database or emailed to you that way?

They have: 53 posts

Joined: Oct 2005

Thanx very much for all your time!
I think I manage it now Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.