While uploading rename file by replacing special character

I have faced some problem to download files which name has special character (like #).  So I have come up a solution by modifying drupal’s core file, includes>file.inc

on file.inc there is a code block like the following,

// Begin building file object.    
$file = new stdClass();   
$file->filename = file_munge_filename(trim(basename($_FILES['files']['name'][$source]), '.'), $extensions);    
$file->filepath = $_FILES['files']['tmp_name'][$source];    
$file->filemime = file_get_mimetype($file->filename);

I have replaced the code with the following code block,

// Begin building file object.     
$file = new stdClass();	 
$file->filename = trim(basename($_FILES["files"]["name"][$source]), '.');	 
$fn = trim(basename($_FILES["files"]["name"][$source]), '.');	 
// split filename based around the . and 3 or 4 letter ext 	 
preg_match("/(^[A-Za-z0-9.].*)(\.[a-z]{3}|\.[a-z]{4})$/", $fn, $matches);	
// replace anything in name ($matches [1]) that is not letter, number or underscore	 
$fn = preg_replace("/[^A-Za-z0-9_]/","_", trim($matches[1]));	 
// remove the dot from .ext suffix	 
$ext = trim($matches[2], '.');	 
//shorten filename to be 54 chars with ext (50+4)	 
$stem = substr($fn, 0, 50);	 
$file->filename = $stem . "." . $ext;     
// Create temporary name/path for newly uploaded files.     
//$file->filepath = tempnam(file_directory_temp(), 'tmp_');    
$file->filepath = $_FILES['files']['tmp_name'][$source];    
$file->filemime = file_get_mimetype($file->filename);


2 Comments to “While uploading rename file by replacing special character”

    • Thanks Attiks. I am not a professional drupal or. PHP developer, just developed 2 sites using drupal. I am used to work with dotNet framework and related tech. I wasn’t aware of that module, though I don’t try that yet. Btw, what country are from? I have checked your site but language is not English.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: