Page 1 of 1

clean file name uploads

Posted: Sat Aug 29, 2009 11:32 pm
by cardi777
Hi all.

I have a cms whereby a file is uploaded and then recorded in a DB.

Code: Select all

    
case "file":
        
if($_FILES[$table_data->f_db_name]['name'] != ""){
$data_insert_query = "UPDATE $db_table_name SET ".$table_data->f_db_name."='".[b]tidyName[/b]($_FILES[$table_data->f_db_name]['name'])."' WHERE unique_id='$newId'";
$db->query($data_insert_query);
        
move_uploaded_file($_FILES[$table_data->f_db_name]['tmp_name'], _base_file_uploads_.tidyName($_FILES[$table_data->f_db_name]['name']));
}
break;
When the file is passed to the processing php page, 2 things happen.

1) file is renamed by going through tidyName() when going into the DB
2) file is renamed by going through tidyName() when being uploaded

It works fine with most files, accept if the file has a ' in it.

For instance, the file is: Beethoven's Symphony No. 9 (Scherzo).wma

Then when uploaded, these are the results:

DB entry = Beethovens_Symphony_No._9_Scherzo.wma
Uploaded filename = Beethoven\s_Symphony_No._9_Scherzo.wma

I get this slash in it when uploaded? NOt sure why.

This is the clean filename class I am using:

Code: Select all

// tidy file name
function tidyName($x){
 
$filename = $x;
 
$invalidFileCharacters = array(
    '*', '<', '>', '+', '"', "'",
    '/', ',', '..', ':', ';', '?',
    '{', '}', '&', '#', '~', '%', '=',
    '[', ']', '(', ')', '@', '^', '`', '!'
);
 
$characters = array(' ', "\t", "\n", "\r", "\0", "\x0B");
$cleanFilename = str_replace($characters, '_', $filename);
 
$cleanFilename = str_replace($invalidFileCharacters, '', $cleanFilename);
 
$cleanFilename = trim($cleanFilename, '._');
 
while(strpos($cleanFilename, '__') !== false){
    $cleanFilename = str_replace('__', '_', $cleanFilename);
}
 
return $cleanFilename;
 
}
Slightly modified from here:http://mywebmind.com/clean-a-filename-w ... #comment-3

The reason is it modified is because I needed to remove some code in order for it to be error free:

Code: Select all

'\',
Not sure whats going on here. If anyone can see whats going on, I would much appreciate it!

Cheers,
Doug

Re: clean file name uploads

Posted: Sun Aug 30, 2009 3:32 pm
by Ollie Saunders

Code: Select all

mysql_real_escape_string() or mysqli_real_escape_string()
Google "SQL injection" as well.

Re: clean file name uploads

Posted: Fri Sep 04, 2009 2:09 am
by cardi777
worked like a charm! thanks