Page 1 of 1

move_uploaded_file security

Posted: Tue Feb 15, 2011 1:21 pm
by Hornpipe2
I have an upload form that does these things:
* executes an external program to check the validity of the uploaded file,
* inserts a new metadata-entry into a mysql table, and
* retrieves the last inserted ID into $new_id

Finally this is called:

move_uploaded_file($_FILES['filedata']['tmp_name'],'/usr/local/www/data/uploads/' . $new_id . '/' . $_FILES['filedata']['name']);

Is this secure? I'm concerned about cracked-out filenames being stored in $_FILES['filedata']['name'] which could include junk like double-dots or forward-slashes. Do scary filenames get escaped in some way by PHP?

Re: move_uploaded_file security

Posted: Tue Feb 15, 2011 2:36 pm
by Mordred
Yes, it's scary, no, PHP will not magically fix it, yes you should do it yourself :)

Re: move_uploaded_file security

Posted: Tue Feb 15, 2011 2:57 pm
by AbraCadaver
As Mordred stated, you need to validate/sanitize it yourself. You can decide what are acceptable characters and check for those, or you could just check for / and either reject it or replace it. Otherwise, I would use this:

Code: Select all

move_uploaded_file($_FILES['filedata']['tmp_name'],'/usr/local/www/data/uploads/' . $new_id . '/' . basename($_FILES['filedata']['name']));

Re: move_uploaded_file security

Posted: Thu Mar 03, 2011 12:12 pm
by xtiano77
Have you thought about storing the file in the database rather than in a folder?

In addition for checking the file for size and invalid characters, you could open the file as a string and search for characters like “<?php”, “?>” and “<% %>” therefore preventing scripts from being uploaded to your site.

Just my two cents!