move_uploaded_file security

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
Hornpipe2
Forum Newbie
Posts: 1
Joined: Tue Feb 15, 2011 1:15 pm

move_uploaded_file security

Post 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?
User avatar
Mordred
DevNet Resident
Posts: 1579
Joined: Sun Sep 03, 2006 5:19 am
Location: Sofia, Bulgaria

Re: move_uploaded_file security

Post by Mordred »

Yes, it's scary, no, PHP will not magically fix it, yes you should do it yourself :)
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: move_uploaded_file security

Post 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']));
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
xtiano77
Forum Commoner
Posts: 72
Joined: Tue Sep 22, 2009 10:53 am
Location: Texas

Re: move_uploaded_file security

Post 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!
Post Reply