Recently I was working on a project and I was required to rename the uploaded files (mostly images) in a way so that it doesn't give away any specific information about the content it is associated with. I thought about for few seconds and realized I can easily do that using timestamp as the file name.
This is what I came up with.add_filter('sanitize_file_name','rename_uploaded_files', 10 );
function rename_uploaded_files($filename) {
// get the filename
$info = pathinfo($filename);
$ext = empty($info['extension']) ? '' : '.' . $info['extension'];
$name = basename($filename, $ext);
// get the current date and time
$date = date('ymdHis');
// rename the file and leave the extension as it is
return $date.$ext;
}
What's Going on?
Well, on this snippet I am using number of PHP functions to gather information about the uploaded file first. In this case it's the file name and it's extension. I am also capturing the current timestamp (including year, month, date, hours, minutes and seconds) to keep the file name to be unique. Because you don't want multiple file names to be the same as it may overwrite the other files with similar file extensions.
Lastly I am passing that unique name to be the name of the file as soon as the uploading process is done. Yes, it would keep the extension of the file intact. I hope you would find this snippet to be helpful. Let me know if you have any additional question of query on this regard. Thanks.
References: sanitize_file_name, add_filter
Comments