clean file name uploads

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
cardi777
Forum Commoner
Posts: 54
Joined: Sun Mar 29, 2009 4:26 am

clean file name uploads

Post 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
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Re: clean file name uploads

Post by Ollie Saunders »

Code: Select all

mysql_real_escape_string() or mysqli_real_escape_string()
Google "SQL injection" as well.
cardi777
Forum Commoner
Posts: 54
Joined: Sun Mar 29, 2009 4:26 am

Re: clean file name uploads

Post by cardi777 »

worked like a charm! thanks
Post Reply